Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make "this" implicit?

Tags:

scala

implicit

I have a class instance of which should be implicitly passed inside methods of this class. Something like this:

class Game(player: Player) {
  protected implicit val implicitThis = this // This is the workaround I use now

  def play = player.makeMove() // makeMove takes an implicit game: Game
}
like image 899
Anton Kuzmin Avatar asked Jun 10 '26 07:06

Anton Kuzmin


1 Answers

You can package it into a trait.

trait ImplicitMe {
  protected implicit def implicitMe: this.type = this
}

class Game extends ImplicitMe {
  private def foo(implicit g: Game) = g
  def bar = foo
}

(Might want to add @inline on the trait also.)

like image 189
Rex Kerr Avatar answered Jun 15 '26 21:06

Rex Kerr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!