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
...
}
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 objects cannot have constructors.
Well, I could change height and width to be vars, and not vals 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.
So, is there a neat way of doing this – i.e. having object vals initialized with values not known before runtime?
Why not use a
classand initialize one instance inmain?