如何制作"这个"隐?

时间:2014-10-05 06:34:02

标签: scala implicit

我有一个类实例应该在这个类的方法中隐式传递。像这样:

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
}

1 个答案:

答案 0 :(得分:1)

您可以将其打包成特质。

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

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

(可能还要在特质上添加@inline。)