1
나는 스칼라로 이해를 위해 시도하는 방법을 배우려고합니다. 아래의 샘플 코드 (결과 1)에서 이해를 위해 처리되지 않은 예외가있는 모나드를 시도하십시오.
,이해가 처리되지 않은 예외가 발생을위한 마지막 문, 코드가 침입하지 않습니다와 시도 [지능]가 반환되는 경우.
그러나 문장의 순서가 이해를 위해 변경되면 (결과 2). 런타임 예외가 발생합니다.
package simpleTryExample
import scala.util.Try
object SimpleTryExample {
def main(args: Array[String]): Unit = {
val result1 = for {
a <- strToInt("3")
b <- strToInt("a")
} yield (a + b)
println("result1 is " + result1)
val result2 = for {
a <- strToInt("a")
b <- strToInt("3")
} yield (a + b)
println("result2 is " + result2)
}
def strToInt(s: String): Try[Int] = {
s match {
case "a" =>
println("input is a")
throw new RuntimeException("a not allowed")
case _ => println("other then a")
}
Try(s.toInt)
}
}
출력 : -
other then a
input is a
Exception in thread "main" java.lang.RuntimeException: a not allowed
at simpleTryExample.SimpleTryExample$.strToInt(SimpleTryExample.scala:30)
at simpleTryExample.SimpleTryExample$.main(SimpleTryExample.scala:18)
at simpleTryExample.SimpleTryExample.main(SimpleTryExample.scala)
result1 is Failure(java.lang.RuntimeException: a not allowed)
input is a
내가 기대했다 result2가 시도 될 [지능]를 입력합니다. 내가 여기서 뭐하고 있는거야 ..?