以下代码
import scala.language.implicitConversions
object myObj {
implicit def nullToInt(x: Null) = 0
def main(args: Array[String]): Unit = {
val x = 1 + null
val y = 1 + nullToInt(null)
println(x + " " + y)
}
}
Run Code Online (Sandbox Code Playgroud)
给出以下结果
1null 1
Run Code Online (Sandbox Code Playgroud)
我期待两个val都是Int并且等于1.
显然,第一个val是String,等于"1null".
Xprint:typer 表明源代码已翻译成
package <empty> {
import scala.language.implicitConversions;
object myObj extends scala.AnyRef {
def <init>(): myObj.type = {
myObj.super.<init>();
()
};
implicit def nullToInt(x: Null): Int = 0;
def main(args: Array[String]): Unit = {
val x: String = …Run Code Online (Sandbox Code Playgroud)