Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize object vals with values known only at runtime?

Tags:

scala

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?

like image 308
Saptamus Prime Avatar asked Jan 08 '12 23:01

Saptamus Prime


People also ask

How do you initialize an object in C++?

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.

Which method is used to initialize the object?

Objects can be initialized using new Object() , Object. create() , or using the literal notation (initializer notation).


1 Answers

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)
  }
}
like image 150
missingfaktor Avatar answered Sep 23 '22 19:09

missingfaktor