繁体   English   中英

是否可以在 Scala 的变量中存储一个尚未定义的 function?

[英]Is it possible to store a function that is yet to be defined in a variable in Scala?

我想做的是有一个非常通用的 class 用于物品。 这些物品会有名称和用途。 它们将被初始化为new Item("Name", function()) ,例如val apple = new Item("Apple", { humanObject.hunger -= 10 }) 通过这种方式,它们稍后可以从 Map 中检索,例如item.Use() ,它会触发上述饥饿值 function,如果它是不同的项目,则可以触发其他内容。

我觉得有一种更聪明的方法可以做到这一点,但我不确定该怎么做。

编辑:

我做了更具体的例子。 这是Item的定义方式:

class Item(val name: String, use: => Unit) {
  def Use() = use
}

以下是它的使用方式:

val example = new Item("Printer", () => println("This printer seems to function!"))

最后,我们可以在其他地方触发 function(让我们忘记 Map 等等)

example.Use()
This printer seems to function!

编辑 2:问题已解决,但如果有人偶然发现此问题,请进一步澄清:我最初没有任何代码,这只是我心中的一个问题。 这个想法是为了避免 inheritance ,这样如果有很多不同的项目,你可以对所有项目使用相同的 model 而不是拥有过多的子类。

似乎你需要的是 inheritance。我不确定name在你的 class 中有什么用,但你可以尝试这样的事情:

abstract class Item(name: String) {
  def use: () => Any
}

class Printer(name: String) extends Item(name) {
  override def use: () => Any = () => println(s"Printer $name seems to function!.")
}

class HumanObject {
  var hunger: Int = 100
}

class Food(name: String, humanObject: HumanObject) extends Item(name) {
  override def use: () => Any = () => humanObject.hunger -= 10
}

val example = new Printer("Printer")
example.use
val food = new Food("apple", new HumanObject())
food.use

我设法自己解决了这个问题,感谢 texasbruce 的指导。

class Item(val name: String, use: => Any) {
  
  var action: () => Any = () => use

  def Use() = action()
}

并使用它:

val example = new Item("Printer", println("This printer seems to function!."))

然后可以按照原始帖子中的说明使用它。

example.Use()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM