[英]Scala:Constant properties val or def
I've got an integer Coordinate Structure for a Hex grid, that I'm porting from C# to Scala as follows: 我已经为Hex网格获得了一个整数坐标结构,将其从C#移植到Scala如下:
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. 由于非基本类型没有常量,因此它们是静态的get属性。 In Scala should I implement them as def s or val s or does it not matter?
我应该在Scala中将它们实现为def或val,还是没关系?
You should implement them as val
. 您应该将它们实现为
val
。 The def
keyword defines a method, so every time it is called, the method will be executed. def
关键字定义了一个方法,因此每次调用该方法时,都会执行该方法。 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. 换句话说,使用
val
, Cood
对象将创建一次并存储,但是使用def
每次您访问它时都会创建一个新副本。
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. 如果您担心创建可能不使用的对象,则应尝试
lazy val
,这是一个仅在首次访问它时填充的val。
You should probably implement your Cood class as a case class : 您可能应该将Cood类实现为case类 :
case class Cood(x: Int, y: Int)
That's it, no need for additional getters / setters, equality method, toString, or extractor for pattern matching. 就是这样,不需要其他getter / setter,相等方法,toString或提取器进行模式匹配。
If you just want it as a normal class, however, just write class Cood(val x: Int, val y: Int)
. 但是,如果只想将其作为普通类,则只需编写
class Cood(val x: Int, val y: Int)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.