0
votes

When I try to compile the following code:

case class A(str: String)
case class B[T <: A](t: T)

def f[T <: A, X <: B[T]](x: X) = {}

f(B(A("str")))

I get the following error:

inferred type arguments [Nothing,B[A]] do not conform to method f's type parameter bounds [T <: A,X <: B[T]]

Why can the compiler not infer that T is of type A?

1

1 Answers

1
votes

When you say:

X <: B[T]

You're defining a new type X that has no type parameters from a type that does have type parameters which confuses the Scala compiler. You're in effect losing T and thus A.

You need to create a type X[C <: A] that is a subtype of B[C] so you preserve the boxed type for your parameter list. Then in your method parameter list you can pass in T directly (which is a subtype of A) to X and the Scala compiler has enough to figure it out.

Therefore the following compiles fine with your example:

def f[T <: A, X[C <: A] <: B[C]](x: X[T])= {}