使用Scala隐式覆盖库方法 [英] override library method using Scala Implicit
问题描述
我正在使用一个类为Product
的库
I'm using a library which has a class Product
like
class Product {
def toString() = "Whatever"
}
我想重写此toString
方法.因此,有两种解决方案.
I want to override this toString
method. So there are two solutions.
1-复制该类的内容,并在自己的项目中创建相同的新类,然后立即使用该方法执行操作.
2-使用Scala Impilicit
1 - Copy the contents of that class and make same new class in you own project and do whatever with that method now.
2 - UseScala Impilicit
第一种方法非常可悲.所以我尝试了第二个,但是面对这个问题.我成功地在该类中添加了新方法,但无法覆盖现有方法.让我用示例来解释它:
1st approach is very pathetic. So I tried the 2nd one, but facing the issue. I'm successful in adding the new method in that class but unable to override the existing one. Let me explain it with example:
class NewProduct(val p: Product) {
override def toString() = "an-other whatever"
}
implicit def customToString(p: Product) = new NewProduct(p)
现在,如果我以这种方式打印println((new Product()).toString)
,它会打印whatever
,但我期望的是an-other whatever
似乎它并没有覆盖该方法,因为如果我添加新方法,它将按预期工作
Now if i prints in this way println((new Product()).toString)
It prints whatever
but I was expecting an-other whatever
It seems that it is not overriding that method, because if I add new Method then it works as expected as
class NewProduct(val p: Product) {
def NewtoString() = "an-other whatever"
}
implicit def customToString(p: Product) = new NewProduct(p)
现在,如果我以这种方式打印println((new Product()).NewtoString)
,它将打印an-other whatever
,其平均新方法NewtoString
已添加到该类.
Now if i prints in this way println((new Product()).NewtoString)
It prints an-other whatever
its mean new Method NewtoString
is added to that class.
我想念的是什么? 是否有可能在Scala中使用impicit覆盖方法?
What I'm missing ? Is it possible to override methods using impicit in Scala ??
推荐答案
如果scala编译器没有它就找不到方法,则使用隐式,因此您不能使用隐式覆盖方法. 为此任务使用继承.
Implicits are used if scala compiler cannot find method without it, so you can`t override methods with implicits. Use inheritance for this tasks.
class NewProduct extends Product {
override def toString() = "an-other whatever"
}
这篇关于使用Scala隐式覆盖库方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!