Given a function with two type parameters, is it possible in scala to pass type parameter for a single type, for example just provide type A
in the example as type B
can be inferred by the compiler from function f
.
def foo[A, B](f: A => B): B = {
f(null.asInstanceOf[A])
}
Right now, I found only two solutions.
Solution 1 (standard usage): Call foo
and specify both types foo[String, Int]( e => 1)
but the definition of Int
is redundant
Solution 2: Change the definition of the function to
def foo[A, B](useType: A => Unit)(f: A => B): B = {
f(null.asInstanceOf[A])
}
and use it with
def use[T](t: T) = {}
val res: Int = foo(use[String]) { a => 1 }
It works, but it does not seems very beautiful to use a function to provide the type to the compiler.
Is there any way to specify just type A
for a function taking two type parameter ?