scala - 有没有办法引用被内联类字段遮蔽的函数参数?

标签 scala

有没有一种方法可以在不命名参数 _name 或在实例化之前重新绑定(bind)参数的情况下引用隐藏参数?

trait Stuff {
  def name: String
}
...
def create (name: String): Stuff = new Stuff {
  // this doesn't work since it references itself
  // how do I make the rhs refer to the parameter, 
  // not the method on the class?
  override def name = name
}

我宁愿保持参数的名称相同,因为调用者可能会使用命名参数。重新绑定(bind)会起作用,但如果有很多参数,那将是很多重复。

最佳答案

这不是问题的直接解决方案,但这可能是在 Scala 中创建对象的更典型的模式:

class NamedStuff(name: String) extends Stuff

def create(name: String): Stuff = new NamedStuff(name)

请注意,NamedStuffname 参数会自动覆盖Stuff 中的name 方法。

关于scala - 有没有办法引用被内联类字段遮蔽的函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68212305/

相关文章:

algorithm - 如何使用 PartialOrdering 对集合进行排序?

scala - 无法在 Windows 上使用 0.13.1 为对象堆保留足够的空间?

java - 提升 json :Custom serializer for java 8 LocalDateTime throwing mapping exception

scala - Spark Streaming mapWithState 似乎定期重建完整状态

scala - 旋转 View 引擎外观相似

scala.collection.immutable.WrappedString 需要隐式 CanBuildFrom 来实现记录的功能吗?

java - 尝试在 scala 中重写 getListCellRenderComponent 方法时出现对象创建不可能错误

scala - 带插件的最小完整 SBT 项目

scala - 随机 bool 生成器

Scala:通用函数乘以不同类型的数字