我正在使用一个Product类似于类的库
class Product {
def toString() = "Whatever"
}
Run Code Online (Sandbox Code Playgroud)
我想覆盖这个toString方法.所以有两种解决方案.
1 - 复制该类的内容并在您自己的项目中创建相同的新类,并立即使用该方法执行任何操作.
2 - 使用Scala Impilicit
第一种方法非常可悲.所以我尝试了第二个,但面对这个问题.我成功地在该类中添加了新方法但无法覆盖现有方法.让我用例子解释一下:
class NewProduct(val p: Product) {
override def toString() = "an-other whatever"
}
implicit def customToString(p: Product) = new NewProduct(p)
Run Code Online (Sandbox Code Playgroud)
现在,如果我以这种方式println((new Product()).toString)打印它打印 whatever但我期待an-other whatever
它似乎没有覆盖该方法,因为如果我添加新方法然后它按预期工作
class NewProduct(val p: Product) {
def NewtoString() = "an-other whatever"
}
implicit def customToString(p: Product) = new NewProduct(p)
Run Code Online (Sandbox Code Playgroud)
现在如果我以这种方式println((new Product()).NewtoString)打印它打印an-other whatever它的平均新方法NewtoString被添加到该类.
我错过了什么?是否有可能在Scala中使用impicit覆盖方法?
如果scala编译器在没有它的情况下找不到方法,则使用Implicits,因此你不能用implicits覆盖方法.使用继承执行此任务.
class NewProduct extends Product {
override def toString() = "an-other whatever"
}
Run Code Online (Sandbox Code Playgroud)