youwei
youwei

Reputation: 49

When should I use type bound in generic class in scala?

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?

Upvotes: 1

Views: 39

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

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.

Upvotes: 3

Related Questions