2

类型推断的哪些变化为Dotty带来了更好的类型推断?Option#fold例如

Starting dotty REPL...
scala> Option(5).fold(Left("err"))(Right(_))
val res0: Either[String, Int] = Right(5)

而在 Scala 2.13.3 中出现错误

scala> Option(5).fold(Left("err"))(Right(_))
                                        ^
       error: type mismatch;
        found   : scala.util.Right[Nothing,Int]
        required: scala.util.Left[String,Nothing]

这似乎与多个参数列表有关,例如Option#fold

fold[B](ifEmpty: => B)(f: A => B): B

在 Scala 2 中的工作如下

这种行为或推断在应用程序类型检查的方式中运行得非常深入,并且它依赖于 foldLeft 等 API,它允许通过考虑第一个参数列表来累积约束,从而允许您省略第二个参数列表中的类型。

但是在上面的示例中它适得其反,因为应用于第二个参数列表的“累积约束”是Left[String,Nothing].

4

0 回答 0