Reputation: 3715
Using scala 2.10
, in scala REPL. I have two definitions of myf
, which is overloaded using different argument type. But when I call myf
(line 7), it calls def myf(data:List[Int])
instead of def myf(data:List[String])
. Despite that the argument itself is of type dataString:List[String]
.
How do I call myf(data:List[String])
inside myf(data:List[Int])
?
I tried to handle type erasure with (implicit d: DummyImplicit)
as shown in here
def myf(data:List[String]) : Unit = {
data.foreach(println)
}
def myf(data:List[Int])(implicit d: DummyImplicit) : Unit = {
val dataString:List[String] = data.map(_ + 1000).map(_.toString) // do something else before toString
myf(dataString:List[String]) // want to call myf(data:List[String]), does not want to call myf(data:List[Int])
}
val d:List[Int] = List(1,2,3)
myf(d)
Errors to:
Name: Compile Error
Message: <console>:50: error: type mismatch;
found : List[String]
required: List[Int]
myf(dataString:List[String]) // want to call myf(data:List[String]), does not want to call myf(data:List[Int])
Upvotes: 0
Views: 87
Reputation: 51271
Here's a REPL session that runs your code.
ShellPrompt> scala #a fresh REPL session
Welcome to Scala 2.12.7 (OpenJDK 64-Bit Server VM, Java 11.0.2).
Type in expressions for evaluation. Or try :help.
scala> :paste
// Entering paste mode (ctrl-D to finish)
def myf(data:List[String]) : Unit = {
data.foreach(println)
}
def myf(data:List[Int])(implicit d: DummyImplicit) : Unit = {
val dataString:List[String] = data.map(_ + 1000).map(_.toString) // do something else before toString
myf(dataString:List[String]) // want to call myf(data:List[String]), does not want to call myf(data:List[Int])
}
val d:List[Int] = List(1,2,3)
myf(d)
// Exiting paste mode, now interpreting.
1001
1002
1003
myf: (data: List[String])Unit <and> (data: List[Int])(implicit d: DummyImplicit)Unit
myf: (data: List[String])Unit <and> (data: List[Int])(implicit d: DummyImplicit)Unit
d: List[Int] = List(1, 2, 3)
Here's a file-compile demonstration.
ShellPrompt> cat so.sc
object SO {
def myf(data:List[String]) : Unit = {
data.foreach(println)
}
def myf(data:List[Int])(implicit d: DummyImplicit) : Unit = {
val dataString:List[String] = data.map(_ + 1000).map(_.toString)
myf(dataString:List[String])
}
def main(args:Array[String]): Unit = {
val d:List[Int] = List(1,2,3)
myf(d)
}
}
ShellPrompt> scalac so.sc -deprecation -explaintypes -feature -unchecked -Xlint -Ypartial-unification
ShellPrompt> scala SO
1001
1002
1003
ShellPrompt>
Upvotes: 1