gpt4 book ai didi

scala - 奇怪的类型推断限制 - 多个类型参数

转载 作者:行者123 更新时间:2023-12-04 08:33:40 26 4
gpt4 key购买 nike

为什么这不能编译?

trait Lol[A, SA] {
def flatMap[B, SB](f: A => Lol[B, SB]): Lol[B, SB] = ???
}

val p1: Lol[Int, String] = ???
val p2: Lol[Double, Nothing] = ???

val p5 = p1.flatMap(_ => p2)

结果:
found   : Int => Lol[Double,Nothing]
required: Int => Lol[Double,SB]
val p5 = p1.flatMap(_ => p2)
^

在以下任一情况下开始编译:
  • flatMap 的类型参数调用是显式的
  • SA是协变的(wtf?)
  • 其他类型而不是 Nothing用于 p2 (例如 Null)
  • SB不会出现在 flatMap 的返回类型中或出现在该返回类型的协变位置(例如返回类型是 Option[SB] )

  • 然而,上述解决方法对我来说是 Not Acceptable 。

    最佳答案

    为了更好地理解您的问题,可以将其简化为:

    class Lol[A]
    def foo[B](f: Lol[B]) = f
    foo(new Lol[Nothing])

    这会给你以下编译错误:
    error: type mismatch;
    found : Lol[Nothing]
    required: Lol[B]
    Note: Nothing <: B, but class Lol is invariant in type A.
    You may wish to define A as +A instead. (SLS 4.5)

    一个可能的解决方案是像这样更新代码段:
    def foo[B <: Lol[_]](f: B) = f

    回到你的原始代码:
    trait Lol[A, SA] {
    def flatMap[B <: Lol[_,_]](f: A => B): B = ???
    }

    关于scala - 奇怪的类型推断限制 - 多个类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32097291/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com