我想出了如何使用TypeTag
将空参数列表添加到现有方法并绕过擦除错误。我想了解我的黑客的工作原理以及是否有更好的方法来实现所需的结果。
我有以下happyStuff
方法:
object Happy {
def happyStuff(s: String): String = {
"happy " + s
}
}
我想更改 happyStuff
的方法签名,然后将旧方法删除如下。
object Happy {
@deprecated("this is the old one")
def happyStuff(s: String): String = {
"happy " + s
}
def happyStuff()(s: String): String = {
"happy " + s
}
}
此代码给出以下错误消息:" def happystuff(s:string(:第6行和def happystuff(((s:string(的字符串:第10行的字符串在擦除后具有相同的类型"。
这个黑客为我带来了我想要的结果:
object Happy {
@deprecated("this is the old one")
def happyStuff(s: String): String = {
"happy " + s
}
def happyStuff[T: TypeTag](x: T)(s: String): String = {
"happy " + s
}
}
TypeTag
如何求解擦除消息?有没有更好的方法来达到预期的结果?
它不是类型标签,而是您放在那里的附加参数:
object Happy {
@deprecated("this is the old one")
def happyStuff(s: String): String = {
"happy " + s
}
def happyStuff[T](x: T)(s: String): String = {
"happy " + s
}
}
也编译。事实是,咖喱在字节码级别上的"消失",因此您最终得到了:
def happyStuff(s: String): String
与
相同def happyStuff()(s: String): String
和
def happyStuff[T](x: T)(s: String): String
与
相同def happyStuff[T](x: T, s: String): String
您可以做
之类的事情sealed trait Deprecated
object Deprecated {
implicit val d: Deprecated = new Deprecated {}
}
object Happy {
@deprecated("this is the old one")
def happyStuff(s: String)(implicit d: Deprecated): String = {
"happy " + s
}
def happyStuff()(s: String): String = {
"happy " + s
}
}
以这种方式,相同的代码将用于旧实现...尽管它会更改签名,因此副本兼容性将丢失。另外,您可能会想出其他一些"版本化代码"的方式,但是最简单/最佳的方法是更改名称(就像其他功能一样(或签名。