从for-comp得到的不会返回我想要的类型

时间:2016-11-01 18:49:31

标签: scala

为什么返回值为val maybeString的Try [Serializable]?我希望它是一个Option [String]

import scala.util.Try

val a1 = Try("fase".toBoolean)
val b2 = Try("100".toInt)

val maybeString: Option[String] = for {
  a <- a1
  b <- b2
} yield (a,b) match {
  case (true, 50) => "foo"
  case (false, 100) => "bar"
  case _ => None
}

println(s"string is $maybeString")

2 个答案:

答案 0 :(得分:3)

  

为什么返回值为val maybeString的Try [Serializable]?

因为scala编译器无法确定您在以下表达式中返回的元素的类型:

(a,b) match {
  case (true, 50) => "foo"
  case (false, 100) => "bar"
  case _ => None
}

您在两种情况下返回String,在另一种情况下返回Option(即None),因此它会选择层次结构中最常见的类型:Serializable

  

我希望它是一个Option [String]

object Test extends App {

  import scala.util.Try

  val a1 = Try("false".toBoolean)
  val b2 = Try("100".toInt)

  val maybeString: Option[String] = for {
    a <- a1.toOption
    b <- b2.toOption
  } yield (a, b) match {
    case (true, 50) => "foo"
    case (false, 100) => "bar"
  }

  println(s"string is $maybeString")
}

答案 1 :(得分:1)

直到最后一刻,您可能无需转换为Option

val maybeString: Option[String] = 
  ( for {
    a <- a1
    b <- b2
    s <- Try(
        (a, b) match {
          case (true, 50) => "foo"
          case (false, 100) => "bar"
        }
      )
  } yield (s)).toOption

在这里,我提取ab(如果它们都成功),for理解的结果有Try[String]类型。然后我可以轻松将其转换为Option[String]

<强>更新

(a, b)不匹配时覆盖案例