1

Let's look at some code first:

trait Foo[T] {
  def fooize(value : T) : Unit
}
object TestFoo {
  def testFooForType[T[_] <: Foo[_]](obj : T[Int]) {
    obj.fooize(5)
  }
}

Why doesn't it typecheck and how can I overcome this difficulty? What I want to do is to test any class that implements the given trait Foo for a particular type T (Int in the example).

1
  • I don't need T as such in the body of testFooForType, you might as well use simply def testFooForType(obj: Foo[Int])... Commented Oct 9, 2014 at 11:55

1 Answer 1

2

T[_] <: Foo[_] means "T forSome type" extends "Foo forSome type".

It has to allow for cases where the types are different. (T[A] extends Foo[B])

Binding T with Int type has no effect on Foo's type, which is still unbounded.

You can either specify Foo's type:

def testFooForType[T[_] <: Foo[Int]](obj : T[_]) {
    obj.fooize(5)
}

or you can make the type relationship explicit:

def testFooForType[T[V] <: Foo[V]](obj : T[Int]) {
    obj.fooize(5)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I was so focused on "T will just be a class extending trait Foo" that I didn't think about that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.