I am new to Scala and I am stuck with a problem which I cannot find a solution online. So I ask for help here.
What I'm trying to do is to implement two map
methods in class A
. The two methods both accept a closure, but for one of them, the type of the return value of the closure is Tuple2
. Also the return values of the two map
methods are NOT of the same class (That's why I need two 'map' methods). The code is simplified as below:
object Test {
class A[T] {
def map[V](a: T => V): A[V] = {
null
}
def map[K, V](a: T => Tuple2[K, V]): B[K, V] = {
null
}
}
class B[K, V] extends A[Tuple2[K, V]] {}
def main(args: Array[String]) {
new A[Int].map(x => x + 1) //compile error
new A[Int].map{x => x + 1} //compile error
new A[Int].map{x:Int => x + 1} //passed but ugly in use
}
}
The definition of class A
and B
and the two map
methods is acceptable by Scala on my computer. Here comes the problem. As I show in main
method how I use the map methods in class A
, the first two statements lead to compilation error (saying missing parameter type of x
in the closure) and only the last one is executable.
And if I delete the second map
method in class A
, the first two statements become executable. I don't know why and how I should do. I just want to keep the two methods sharing the same name map
and meanwhile I don't need to tell the type of parameters of the closure when using map
methods.
Hope anyone interested in this question and offer me a better design. Thanks in advance.