Следующий код
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.
По-видимому, первый 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 = 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", и "null" были преобразованы в строку вместо применения неявного nullToInt. Кто-нибудь может объяснить, как компилятор до этого додумался? Какая логика/рабочий процесс использовались?
И еще вопрос: есть ли способ включить неявный nullToInt?
PS. Я не говорю о лучших практиках здесь. Не стесняйтесь рассматривать вопрос как предмет академического интереса.
+
с любым другим методом (здесь+++
):import language.implicitConversions; class I { def +++(i: I) = "I +++ I" }; class S { def +++(a: Any) = "S +++ Any" }; class N; implicit def n2i(n: N): I = new I; implicit def i2s(i: I): S = new S; println((new I) +++ (new N));
Это преобразуетN
вI
и вызывает+++
изI
, а не изS
. Я не уверен, почему это работает наоборот с+
. - person Andrey Tyukin   schedule 28.09.2018