2017-10-15 1 views
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가 시도 될 [지능]를 입력합니다. 내가 여기서 뭐하고 있는거야 ..?

답변

2

문제는 두 번째 예에서 Try[T] 컨텍스트를 입력하기 전에 예외가 발생한다는 것입니다. strToInt의 첫 번째 호출이 성공적이기 때문에

strToInt("3").flatMap(_ => strToInt("a")) 

은, 모든 후 실행 : strToInt("a")을 실행할 때 첫 번째 예에서

코드가에 desugered되기 때문에, 당신은 Try[T]의 맥락에서 이미있어 그것은 이해를위한 내용으로 Try의 문맥에있다. 우리가 Try 맥락에서 여전히을 을하지 않은 이후로 당신이 Ints을 구문 분석 할 때

strToInt("a").flatMap(_ => strToInt("3")) 

strToInt("a")이 적용 전용하는 RuntimeException을 던질 것이다 : 그러나, 두 번째 예제에서, 우리는 반대를 .

def strToInt(s: String): Try[Int] = { 
    Try { 
    s match { 
     case "a" => 
     println("input is a") 
     throw new RuntimeException("a not allowed") 
     case _ => println("other then a") 
    } 
    s.toInt 
    } 
} 

그리고 지금 우리가 얻을 :

other then a 
input is a 
result1 is Failure(java.lang.RuntimeException: a not allowed) 
input is a 
result2 is Failure(java.lang.RuntimeException: a not allowed) 

는 패턴 경기 전에 최대 높은 시도 이동, 모두이 문제를 방지하려면
관련 문제