Reputation: 27604
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?
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.
Upvotes: 3
Views: 79
Reputation: 40500
null
is just assigning a default value to the ev
, just like you would to any other parameter.
It is a clever way to find out whether the type is actually an 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.
So, by checking if ev
is null
, you can tell whether or not the implicit was available at call site.
Upvotes: 6