I have a generic class like this and I only want function "one" to be called when T is Int.
class A[T] {
def one[T <: Int] = 1
}
val a = new A[String]
a.one
But this compiles.
I find that I can do this:
class A[T] {
def one(implicit ev: T <:< Int) = 1
}
val a = new A[String]
a.one
<console>:14: error: Cannot prove that String <:< Int.
Why?
In the first case you have two different and unrelated T
parameters: one on the class, another on the method. So when you call a.one
, one
's T
is Int
.
In the second case one
doesn't have its own T
parameter, so in T <:< Int
you have A
's T
. When you call a.one
, A
's T
is String
which doesn't satisfy the bound.
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.