scala - 混合隐式、类型参数和Nothing时编译错误

标签 scala implicit

为什么这不能用类型参数编译:

error: value explode is not a member of Test.A[Nothing]



如果我删除它们,那么它会编译。我不明白什么,更重要的是,我能做些什么来解决它。
object Test extends App {

  implicit class B[E](set: A[E]) {
    def explode() = println("boom")
  }

  case class A[E](name: String)

  A[Nothing]("coldplay").explode()
}

(这个例子中的类型参数不做任何事情,但在现实世界的用例中我有多个类型参数,有些可以是 Nothing ,有些不是)。

最佳答案

它真的不喜欢推断 Nothing:

scala> implicit def a2b(a: A[Nothing]): B[Nothing] = new B(a)
<console>:17: error: type mismatch;
 found   : A[Nothing]
 required: A[T]
Note: Nothing <: T, but class A is invariant in type E.
You may wish to define E as +E instead. (SLS 4.5)
       implicit def a2b(a: A[Nothing]): B[Nothing] = new B(a)
                                                           ^

scala> implicit def a2b(a: A[Nothing]): B[Nothing] = new B[Nothing](a)
warning: there were 1 feature warning(s); re-run with -feature for details
a2b: (a: A[Nothing])B[Nothing]

scala> A[Nothing]("coldplay").explode()
boom
-Ytyper-debug :
|    |    |    |    |    |    |    solving for (T: ?T)
|    |    |    |    |    |    |    |-- $iw.this.X.B BYVALmode-EXPRmode-FUNmode-POLYmode (silent solving: type T: method f in X) implicits disabled
|    |    |    |    |    |    |    |    [adapt] [T](set: $line3.$read.$iw.$iw.X.A[T])$line3.$read.$iw.$iw... adapted to [T](set: $line3.$read.$iw.$iw.X.A[T])$line3.$read.$iw.$iw...
|    |    |    |    |    |    |    |    \-> (set: X.A[T])X.B[T]
|    |    |    |    |    |    |    solving for (T: ?T, T: ?T)
|    |    |    |    |    |    |    \-> <error>
<console>:10: error: value explode is not a member of X.A[Nothing]
       def f() = A[Nothing]("coldplay").explode() }

关于scala - 混合隐式、类型参数和Nothing时编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23759787/

相关文章:

Scala:比较类型

perl - 为什么 "import"子程序在 Perl 中没有大写

c# - 等效的隐式运算符 : why are they legal?

scala - 从 Spark 写入 DynamoDB

scala - 在 Scala 中,如何在对该变量的列表进行排序之前将方法应用于变量?

scala - 如何控制从 Spark DataFrame 写入的输出文件的数量?

scala - 如何询问 Scala 是否存在所有类型参数实例化的证据?

scala - scalaz.Equal 是如何解决的

scala - Scala 3 中的类型模式匹配和推理错误

scala - 启动使用 one-jar 创建的 jar 时出错