rah rah - 2 months ago 5x
Scala Question

Restrict Generic function fun[T] with multiple parameters on higher types on T to be exactly T

I have the following function

def f[T](l:List[T], v:T)

this works without errors for

f(List(1,2,3), "this is a string")

even when T is not same in both parameters. Is it possible to rewrite the function so that the compiler gives me an error when T is not same in both parameters? (I cant rely on the user to explicitly specify the type in function f[Int])

[Apologies for the horrible title]


Type unification happens only within a parameter list. You can use separate parameter lists, although this only ensures that v.type <:< T, not that v.type =:= T.

def f[T](l:List[T])(v:T): List[T] = v :: l

f(List(1,2,3))("this is a string")

Error:(81, 20) type mismatch;
found   : String("this is a string")
required: Int
f(List(1,2,3))("this is a string")

Another option is using an implicit, although it requires a type cast:

def f[T, U](l: List[T], v: U)(implicit ev: T =:= U): List[T] =
  v.asInstanceOf[T] :: l

val l1 = List("a", "b", "c")
val l2: List[Any] = List("a", "b", "c")

val s1 = "d"
val s2: Any = "d"

f(l1, s1) // compiles
f(l2, s2) // compiles
f(l1, s2) // Cannot prove that String =:= Any.
f(l2, s1) // Cannot prove that Any =:= String.