override library method using Scala Implicit
Asked Answered
W

1

6

I'm using a library which has a class Product like

class Product {
   def toString() = "Whatever"  
}

I want to override this toString method. So there are two solutions.

1 - Copy the contents of that class and make same new class in you own project and do whatever with that method now.
2 - Use Scala 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)

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)

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.

What I'm missing ? Is it possible to override methods using impicit in Scala ??

Whichsoever answered 22/6, 2015 at 8:38 Comment(0)
I
7

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"
}  
Institution answered 22/6, 2015 at 8:48 Comment(3)
so what can I do in this situation ? I've a Jar containing that class, now what can i do to override that method ?Whichsoever
inheritance is the key word.Romanaromanas
the recommended way is inheritance. but there are situations when you can not simply inherit (class is final or the api has a very deep structure). then the only options you have is either replacing that class in the jar or byte code manipulation - both options are ugly ..Chalcanthite

© 2022 - 2024 — McMap. All rights reserved.