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 object
s cannot have constructors.
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.
So, is there a neat way of doing this - i.e. having object val
s initialized with values not known before runtime?
There are two ways to initialize a class object: Using a parenthesized expression list. The compiler calls the constructor of the class using this list as the constructor's argument list. Using a single initialization value and the = operator.
Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation).
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With