Freewind
Freewind

Reputation: 198318

Implicit class can't apply to self-type?

I've defined a class and an implicit class:

class User
implicit class RichUser(user: User) {
  def hello = println("hello")
}

Following code is working well:

val user = new User
user.hello

But following code is not compilable:

trait UserTrait {
  this: User =>

  this.hello // can't compile !!!
}

Why can't it compilable, and how to fix it?


Update:

Sorry, it doesn't compile in IntelliJ IDEA, and I didn't try with scalac. Thanks for all.

idea-error

Upvotes: 1

Views: 310

Answers (1)

Landei
Landei

Reputation: 54584

Not nice, but you can always call the implicit explicitly (pun intended)

trait UserTrait {
  this: User =>

  implicitly[RichUser](this).hello 
}

Upvotes: 2

Related Questions