I’ve got an integer Coordinate Structure for a Hex grid, that I’m porting from C# to Scala as follows:
object Cood
{
def Up = new Cood(0, 2)
def UpRight = new Cood(1, 1)
def DownRight = new Cood(1,- 1)
def Down = new Cood(0, - 2)
def DownLeft = new Cood(- 1, - 1)
def UpLeft = new Cood(- 1, + 1)
def None = new Cood(0, 0)
}
class Cood(val x: Int, val y: Int)
{
//more code
}
As there were no constants for non basic types they were static get properties. In Scala should I implement them as def s or val s or does it not matter?
You should implement them as
val. Thedefkeyword defines a method, so every time it is called, the method will be executed. In other words, withvaltheCoodobject will be created once and stored, but withdefa new copy will be created every time you go to access it.If you are worried about creating object that may not be used, then you should try
lazy val, which is a val that is only populated the first time it is accessed.