Scala - 明确引用参数

时间:2017-06-24 21:55:09

标签: scala

鉴于这个完全专业的Scala这个很棒的作品:

trait SomethingCool {
  def foo: Int => String
}

def makeSomethingCool(foo: Int => String = i => i.toString): SomethingCool = {
  new SomethingCool {
    override def foo = foo // method foo does nothing other than call itself recursively
  }
}

我有一个具有默认实现的特征的工厂方法,如何从new SomethingCool { }中引用参数名称?它似乎被特质的功能名称掩盖了。

1 个答案:

答案 0 :(得分:4)

你做不到。但这是一个解决方法:

def makeSomethingCool(foo: Int => String = i => i.toString): SomethingCool = {
  val _foo = foo
  new SomethingCool {
    override def foo = _foo
  }
}