斯卡拉如何使用正确的签名调用重载方法

时间:2019-04-25 06:46:41

标签: scala

在scala REPL中使用scala 2.10。我有两个myf的定义,它们使用不同的参数类型来重载。但是,当我致电myf(第7行)时,它将呼叫def myf(data:List[Int])而不是def myf(data:List[String])。尽管参数本身是dataString:List[String]类型。

如何在myf(data:List[String])内致电myf(data:List[Int])

我尝试用(implicit d: DummyImplicit)处理类型擦除,如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)

错误:

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])

1 个答案:

答案 0 :(得分:1)

这是一个运行您的代码的REPL会话。

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)

这是文件编译演示。

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>