假设我有以下Java方法:
protected void onEvent(Object obj) {
}
Scala编译器接受
protected override def onEvent(event: Any)
并且
protected override def onEvent(event: Object)
这两者有什么区别吗?
假设我有以下Java方法:
protected void onEvent(Object obj) {
}
Scala编译器接受
protected override def onEvent(event: Any)
并且
protected override def onEvent(event: Object)
这两者有什么区别吗?
Any
包括在Java中不是 Object
的东西;它包括基本类型和 Nothing
。 Object
是Java中相同的类,因此它肯定不包括基本类型。
在scala-lang的文章中有一个很棒的图表(我甚至把它挂在了墙上)。还需要提到的是:
如果Scala在Java运行时环境中使用,则scala.AnyRef对应于java.lang.Object。
def met(a: java.lang.Object) = {}; val i = 10; met(i)
,这是编译器的输出:error: the result type of an implicit conversion must be more specific than AnyRef。https://dev59.com/518d5IYBdhLWcg3wsT0b#26550576,使用val i: java.lang.Integer = 10
(而不是默认的val i: Int = 10
)可以解决问题。 - Nicofisi