Parameter type inference in scala
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 ?
Generally no, type parameters can't be partially applied in Scala. Neither in methods nor in classes. Some wrappers can be used:
def myMethod[A, B]() = ???
def myMethod1[A0, W <: Wrapper { type A = A0 }]() = ???
trait Wrapper {
type A
type B
}
Maybe with some path-dependent types:
def myMethod1[A0, W <: Wrapper { type A = A0 }](w: W)(): w.B = ???
And in case of not methods but classes there are approaches with type lambdas and type members (type members can be partially applied: Wrapper { type A = A0 }
for trait Wrapper { type A; type B }
is an existential type like Wrapper[A0, _]
for trait Wrapper[A, B]
).
Partially applying type parameters
链接地址: http://www.djcxy.com/p/38030.html上一篇: 用于同步MySQL数据库的最佳工具
下一篇: scala中的参数类型推断