scala可以从`Long`隐式转换为`AnyRef`吗
can scala implicit convert from `Long` to `AnyRef`
def testLong(v: Any): Unit = {
println(v.getClass) // print: class java.lang.Long
}
testLong(103L) // compile passed
从最后一个片段中,它表明变量 v
是 class java.lang.Long
。它是 java.lang.Object
的子类。
我们也从 scala Unified types 系统知道 AnyRef
等于 java.lang.Object
类型。但是编译失败的原因如下:
def testLong(v: AnyRef): Unit = {
println(v.getClass)
}
testLong(103L) // compile failed
第二个例子中没有使用隐式转换的原因可能是因为:
// val l: AnyRef = 10L
// error: the result type of an implicit conversion must be more specific than AnyRef.
这 answer 可以很好地解释为什么会发生这种情况。
但是,您可以使用隐含证据重写您的方法以使其工作。
def testLong[T](v: T)(implicit ev: T => AnyRef): Unit = {
println(v.getClass)
}
testLong(10L)
// class java.lang.Long
奇怪的是,如果您使该方法仅特定于 Long,打印的 class 会发生变化。
def testLong(v: Long)(implicit ev: Long => AnyRef): Unit = {
println(v.getClass)
}
testLong(10L)
// long
def testLong(v: Any): Unit = {
println(v.getClass) // print: class java.lang.Long
}
testLong(103L) // compile passed
从最后一个片段中,它表明变量 v
是 class java.lang.Long
。它是 java.lang.Object
的子类。
我们也从 scala Unified types 系统知道 AnyRef
等于 java.lang.Object
类型。但是编译失败的原因如下:
def testLong(v: AnyRef): Unit = {
println(v.getClass)
}
testLong(103L) // compile failed
第二个例子中没有使用隐式转换的原因可能是因为:
// val l: AnyRef = 10L
// error: the result type of an implicit conversion must be more specific than AnyRef.
这 answer 可以很好地解释为什么会发生这种情况。
但是,您可以使用隐含证据重写您的方法以使其工作。
def testLong[T](v: T)(implicit ev: T => AnyRef): Unit = {
println(v.getClass)
}
testLong(10L)
// class java.lang.Long
奇怪的是,如果您使该方法仅特定于 Long,打印的 class 会发生变化。
def testLong(v: Long)(implicit ev: Long => AnyRef): Unit = {
println(v.getClass)
}
testLong(10L)
// long