Why does implicit conversion in the constructor require 'this'?

Consider the following typical Scala 'pimp' code:

class PimpedA(a:A){ def pimp() = "hi" } implicit def pimpA(a:A) = new PimpedA(a) new A(){ pimp() //<--- does not compile } 

However, changing it to:

 new A(){ this.pimp() } 

It makes it work. Shouldn't this match up with the Scala compiler?

EDIT : Is there any solution that can make it work without having to add this. ?

+4
source share
2 answers

In this case, you should give the compiler an indication that pimp() not a random function. When you write

 this.pimp() 

the compiler knows that class A does not have a pimp function, therefore, before failure, it searches for an implicit conversion in scope and finds it.

 pimpA(this).pimp() 

And when you just call pimp() , the compiler does not know which object should go to the implicit function pimpA(a: A) .

UPDATE

It’s hard to understand what your goal is. I can offer only the PimpedA class ( Pimp[T] in this example).

 trait Pimp[T] { def action(p: T): String } implicit object PimpA extends Pimp[A] { override def action(p: A) = "some actions related to A" } def pimp[T: Pimp](p: T) = implicitly[Pimp[T]].action(p) class A { val foo = pimp(this) } scala> new A foo res2: String = some actions related to A 
+2
source

Not at all. For it to work, pimp must be either an object or an imported value element, and this is not the case. The class has an "implicit" import this._ . It does not have a mechanism that automatically adds this to the file to find out if it compiles.

+5
source

Source: https://habr.com/ru/post/1382076/


All Articles