简体   繁体   中英

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?


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 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM