[英]What does “T =:= Int = null” mean in Scala?
As in the following code. 如下面的代码所示。
class A[T] {
def add(n: Int)(implicit env: T =:= Int = null): Int = n + 1
}
object A extends App {
val a = new A[Int]
a.add(1) // 2
}
I know that T =:= Int
means T
should be of type Int
, but what does = null
part mean? 我知道
T =:= Int
意味着T
应该是Int
类型,但是= null
部分是什么意思?
Note : The example is made up by me. 注意 :这个例子由我组成。 It'd be better if you can show me a proper usage of
= null
if it's not appropriate. 如果你不合适的话可以向我展示
= null
的正确用法,那会更好。
null
is just assigning a default value to the ev
, just like you would to any other parameter. null
只是为ev
分配一个默认值,就像你对任何其他参数一样。 It is a clever way to find out whether the type is actually an Int
: 这是一个聪明的方法来确定该类型是否实际上是一个
Int
:
def isInt[T](implicit ev: T =:= Int = null): Boolean = env != null
isInt[Int] // true
isInt[String] // false
The trick is that when compiler sees the Int
, it will pass in the actual implicit value, and when it can't find one, it'll just leave it as default. 诀窍是当编译器看到
Int
,它将传递实际的隐式值,当它找不到时,它只是将其保留为默认值。 So, by checking if ev
is null
, you can tell whether or not the implicit was available at call site. 因此,通过检查
ev
是否为null
,您可以判断隐含在调用站点是否可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.