Следующий код
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)
}
}
дает следующий результат
1null 1
Я ожидал, что оба значения будут равны Int и равны 1.
Видимо, первое значение - 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 = 1.+(null);
val y: Int = 1.+(myObj.this.nullToInt(null));
scala.Predef.println(x.+(" ").+(y))
}
}
}
Нет никаких символических методов для int, которые принимают null
scala> 10+null
res0: String = 10null
scala> 10*null
<console>:12: error: overloaded method value * with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: Int)Int <and>
(x: Char)Int <and>
(x: Short)Int <and>
(x: Byte)Int
cannot be applied to (Null)
10*null
^
scala> 10-null
<console>:12: error: overloaded method value - with alternatives:
(x: Double)Double <and>
(x: Float)Float <and>
(x: Long)Long <and>
(x: Int)Int <and>
(x: Char)Int <and>
(x: Short)Int <and>
(x: Byte)Int
cannot be applied to (Null)
10-null
^
Я предполагаю, что и «1», и «ноль» были преобразованы в строку вместо применения неявного nullToInt.Может кто-нибудь объяснить, , как компилятор придумал это?Какая логика / рабочий процесс использовался?
И еще вопрос , есть ли способ включить implcit nullToInt?
PS.Я не говорю о лучших практиках здесь.Не стесняйтесь рассматривать вопрос как вопрос академического интереса.