Reputation: 6109
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?
Upvotes: 1
Views: 374
Reputation: 51109
You should probably implement your Cood class as a case class:
case class Cood(x: Int, y: Int)
That's it, no need for additional getters / setters, equality method, toString, or extractor for pattern matching.
If you just want it as a normal class, however, just write class Cood(val x: Int, val y: Int)
.
Upvotes: 2
Reputation: 52681
You should implement them as val
. The def
keyword defines a method, so every time it is called, the method will be executed. In other words, with val
the Cood
object will be created once and stored, but with def
a 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.
Upvotes: 5