Option.toRight返回产品类型.这是什么意思



这是我上一个问题的后续内容。评论中指出,toRight返回Product with Serializable with scala.util.Either:

scala> val ox = Some(0)
ox: Some[Int] = Some(0)
scala> ox.toRight("No number")
res0: Product with Serializable with scala.util.Either[String,Int] = Right(0)

现在我想知道它与我需要的Either类型有何不同。我应该像那样明确地添加Either[String,Int]吗?

scala> ox.toRight("No number"): Either[String, Int]
res1: Either[String,Int] = Right(0)

类型

Product with Serializable with scala.util.Either[String,Int]

只是过于具体,因为编译器能够确定它是ProductSerializable,即使您不关心这些事情。这只是因为编译器总是告诉你它能确定的最具体的类型,因为它自然不知道你想要什么级别的特殊性。但它告诉你它是with scala.util.Either[String,Int],这就是你想要的,所以你不需要担心额外的东西。如果您想使类型更简单,那么是的,只需显式声明即可。

最新更新