使用Either的Eclipse方法签名

时间:2018-03-08 22:01:41

标签: scala

如果您在Eclipse中输入以下代码并将鼠标悬停在f2以显示方法签名,那就错了。仅当方法返回Future Either时才会发生这种情况。

鉴于此代码:

object HelloScala extends App{

      def f1 = Future { 1 }

      def f2 = {
        val future = f1
        future.map { 
           case i: Int => Right(1)
           case _ => Left(0)
         }
      }

      Thread.sleep(10000)
}

而不是Future[Either[Int,Int]],我看到了这一点:

enter image description here

任何想法,如果这是可以解决的?

1 个答案:

答案 0 :(得分:1)

The type Eclipse shows (which is the type inferred by the Scala compiler) is not wrong, it's the most accurate type the compiler could find. Why?

All the compiler knows is that this Future will either hold a Left[Int] or a Right[Int]; Both of these types extend these 3 traits:

  • Either[Int, Int] as expected
  • Product because both Left and Right are case classes, and all case classes extend Product; and
  • Serializable for the same reason (all case classes are Serializable)

So the inferred type is the combination of all three.

You can easily fix it by explicitly specifying the desired type yourself when calling map:

def f2 = {
  val future = f1
  future.map[Either[Int, Int]] {
    case i: Int => Right(1)
    case _ => Left(0)
  }
}