使用Scala Implicit重写库方法
发布时间:2020-12-16 18:05:44 所属栏目:安全 来源:网络整理
导读:我正在使用一个类似于Product的库 class Product { def toString() = "Whatever" } 我想重写这个toString方法.所以有两种解决方案. 1 – Copy the contents of that class and make same new class in you own project and do whatever with that method now
我正在使用一个类似于Product的库
class Product { def toString() = "Whatever" } 我想重写这个toString方法.所以有两种解决方案.
第一种方法非常可悲.所以我尝试了第二个,但面对这个问题.我成功地在该类中添加了新方法但无法覆盖现有方法.让我用例子解释一下: class NewProduct(val p: Product) { override def toString() = "an-other whatever" } implicit def customToString(p: Product) = new NewProduct(p) 现在,如果我以这种方式打印println((new Product()).toString)它打印任何东西,但我期待的其他什么 class NewProduct(val p: Product) { def NewtoString() = "an-other whatever" } implicit def customToString(p: Product) = new NewProduct(p) 现在,如果我以这种方式打印println((new Product()).NewtoString)它会打印另一个 – 无论它的平均新方法NewtoString被添加到该类. 我错过了什么? 解决方法
如果scala编译器在没有它的情况下找不到方法,则使用Implicits,因此你不能用implicits覆盖方法.
使用继承执行此任务. class NewProduct extends Product { override def toString() = "an-other whatever" } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |