Why doesn't Scala fully infer type parameters when type parameters are nested?

Viewed 6660

Consider the following Scala code:

abstract class A
abstract class B[T <: A]
class ConcreteA extends A
class ConcreteB extends B[ConcreteA]

class Example[U <: B[T], T <: A]( resolver: U )
object Test {
    new Example( new ConcreteB )
}

The last line new Example( new ConcreteB ) fails to compile with the following error:

error: inferred type arguments [ConcreteB,Nothing] do not conform to class Example's type parameter bounds [U <: B[T],T <: A]

But ConcreteB has all the necessary data to resolve both U and T. What am I missing here?

4 Answers

It works in Scala 3 which has improved inference so the workarounds above are no longer necessary. For example type parameters do not have to always be surfaced in the (value) parameter list to be inferred so we can write

def f[F <: List[A], A](as: F)

instead of

def f[F <: List[A], A](as: F[A])

for example

āžœ  ~ scala3-repl -version
Scala code runner version 3.0.0-RC2 -- Copyright 2002-2021, LAMP/EPFL
āžœ  ~ scala3-repl         
scala> def f[F <: List[A], A](as: F) = as                                                                                                                
def f[F <: List[A], A](as: F): F

scala> f(List(42))                                                                                                                                       
val res0: List[Int] = List(42)

where we see F was inferred as List and A was inferred as Int.

Related