有可能在Scala中的变量中存储尚未定义的函数吗



我想做的是为项创建一个非常通用的类。这些物品将有一个名称和用途。它们将被初始化为例如val apple = new Item("Apple", { humanObject.hunger -= 10 })。这样,以后就可以从Map(例如item.Use()(中检索它们,然后CCD_3会启动前面提到的饥饿功能,或者如果它是不同的项目,则可以启动其他功能。

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

编辑:

我举了更具体的例子。这就是Item的定义:

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

以下是它的使用方法:

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

最后,我们可以在其他地方启动该功能(让我们忘记地图之类的(

example.Use()
This printer seems to function!

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

似乎您需要的是继承。我不确定name在你的基类中有什么用,但你可以试试这样的东西:

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

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

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()

最新更新