Why is Scala's behavior in case of overloading with by-name parameters different from the case with by-value parameters?

柔情痞子 提交于 2019-12-05 02:33:34

That's because JVM does not support a "by-name" parameter, so Scala has to implement it in another way. => X actually compiles to a Function0[X], which erases to Function0[Object], which makes it impossible for Scala to distinguish two methods that differ only by the expected type of a by-name parameter.

Possible workaround without overloading (in addition to what has been said earlier), if you don't want to use different method names:

def byname[A](a: => A)(implicit manifest:Manifest[A]) = 
manifest.erasure match {
   case erasure if(erasure.isAssignableFrom(classOf[Long])) => println("=> Long")
   case erasure if(erasure.isAssignableFrom(classOf[Int])) => println("=> Int")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!