开发者

Overloading in Scala when type parameters are being used

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?


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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜