Overloading in Scala when type parameters are being used

我怕爱的太早我们不能终老 提交于 2019-12-12 02:14:08

问题


Look at this piece of code I am working on at the moment (It's meant to parse some arguments from the arguments of the main method):

def parser[T](identifier: String, default: T, modifier: String => T): T = {
  val l = args.filter(_.startsWith(identifier))
  if(l.isEmpty) default
  else modifier(l(0).drop(identifier.length).trim)
}

I also intended to write an overloaded method that deals with the case of Strings:

def parser(identifier: String, default: String): String = parser[String](identifier, default, identity)

The compiler does not seem to be impressed with this and will not allow me to overload the method. I have to change the name of either of the methods to make this work:

def parser(identifier: String, default: String): String = genParser[String](identifier, default, identity)

Is there a reason I can't overload when type parameters are in use?


回答1:


Overloading is not what the compiler is concerned about.

<console>:8: error: method parser: (identifier: String, default: String) String does not take type parameters.

This code:

parser[String](identifier, default, identity)

calls this method:

def parser(identifier: String, default: String): String

instead of this one as you would want:

def parser[T](identifier: String, default: T, modifier: String => T): T

This illustration compiles just fine:

val args = Array[String]()

def parser[T](identifier: String, default: T, modifier: String => T): T = {
  val l = args.filter(_.startsWith(identifier))
  if(l.isEmpty) default
  else modifier(l(0).drop(identifier.length).trim)
}

def parser(identifier: String, default: String): String = "dummy"


来源:https://stackoverflow.com/questions/7319196/overloading-in-scala-when-type-parameters-are-being-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!