【发布时间】:2020-08-07 00:43:37
【问题描述】:
我有以下 sn-p,它(我认为)在泛型类型 T 上定义了一个方法 addNumber1(x:T):T,它是 AnyVal 的子类型,并且有一个方法 +(s:Int):T。
def addNumber1[T <: AnyVal {def +(s:Int):T}](x:T):T = {x + 1}
addNumber1(31) // compiles but throws exception
java.lang.NoSuchMethodException: java.lang.Integer.$plus(int)
at java.lang.Class.getMethod(Class.java:1786)
at .reflMethod$Method1(<console>:8)
at .addNumber1(<console>:8)
... 33 elided
我尝试添加 import scala.language.reflectiveCalls 来抑制功能警告,但仍然出现错误。
我可以在使用AnyRef 或Any 时使用它,如下所示:
def addNumber1[T <: Any {def +(s:Int):T}](x:T):T = {x + 1}
class Foo(s:String) {def +(i:Int) = new Foo((s+1).toString)} // random code
class Bar(s:Foo) {def +(i:Int) = new Bar(new Foo(i.toString))} // random code
addNumber1(new Foo("1")) // works
addNumber1(new Bar(new Foo("1"))) // works
addNumber1(1) // compiles but gives exception
【问题讨论】: