Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override library method using Scala Implicit

Tags:

scala

implicit

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 ??

like image 609
Zia Kiyani Avatar asked Jun 22 '15 08:06

Zia Kiyani


1 Answers

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"
}  
like image 96
Dmitry Meshkov Avatar answered Nov 15 '22 04:11

Dmitry Meshkov