Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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?

like image 945
Tomer Gabel Avatar asked Jul 31 '11 22:07

Tomer Gabel


1 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.

like image 60
Mario Galic Avatar answered Oct 18 '22 09:10

Mario Galic