如何使用仅在运行时已知的值初始化对象 val? [英] How do I initialize object vals with values known only at runtime?
问题描述
假设我正在尝试编写一个简单的井字游戏.它有一个 M x N 字段.游戏只有一个字段,所以它可能应该用一个单独的 object
来表示.像这样:
Let's say I'm trying to write a simple Tic-Tac-Toe game. It has an M x N field. The game has only one field, so it probably should be represented with a singleton object
. Like this:
object Field {
val height : Int = 20
val width : Int = 15
...
}
但我不想硬编码高度和宽度,所以如果它们可以在运行时通过构造函数或其他东西传递给对象,那就太好了.但是 object
不能有构造函数.
But I don't want to hardcode the height and width, so it would be nice if those could be passed to the object at runtime, via a constructor or something. But object
s cannot have constructors.
好吧,我可以将 height
和 width
改为 var
s,而不是 val
s 并引入一种新方法
Well, I could change height
and width
to be var
s, and not val
s and introduce a new method
def reconfigure (h:Int, w:Int) = {
height = h
width = w
}
并在游戏开始时调用它.但它也不优雅.
and call it at the begining of the game. But it's not elegant as well.
那么,有没有一种巧妙的方法可以做到这一点 - 即使用运行前未知的值初始化对象 val
?
So, is there a neat way of doing this - i.e. having object val
s initialized with values not known before runtime?
推荐答案
为什么不使用 class
并在 main
中初始化一个实例?
Why not use a class
and initialize one instance in main
?
case class Field(width: Int, height: Int) {
//...
}
object Main {
def main(args: Array[String]): Unit = {
val field = Field(30, 25)
}
}
这篇关于如何使用仅在运行时已知的值初始化对象 val?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!