scala get/set 几种写法
1.说明
scala 没有修饰符的方法或者是属性 默认是public的
- scala 的get/set 方法是自动生成的
- var修饰的变量会生成get/set方法
- val修饰的变量只生成get方法不生成set方法
- 对于private修饰的 变量,scala生成的get/set 也是私有的
2.若要想访问私有的变量,必须重新定义get/set
class obb() {
private[this] var mprivateAge: Int = 0
def privateAge: Int ={
println("调用了get")
this.mprivateAge
}
def privateAge_=(value: Int): Unit = {
print("调用了set")
this.mprivateAge = value
}
}
object obb {
def main(args: Array[String]): Unit = {
val o= new obb()
println(o.privateAge) //实际上调用的是方法
o.privateAge = 99
print(o.privateAge) //实际上调用的是方法
}
观察上面的结果和代码,你会发现这种写法其实完全隐藏了内部的属性 mprivateAge,.
无论是访问还是赋值都用的privateAge这个名字, 看起来就像privateAge才是属性一样,其实不然,privateAge是方法.
3.注解生成(scala/java 双版本)的 set/get
import scala.beans.BeanProperty
class obb() {
@BeanProperty var mprivateAge: Int = 0
}
object obb {
def main(args: Array[String]): Unit = {
val o= new obb()
println(o.getMprivateAge)
o.setMprivateAge(99)
print(o.getMprivateAge)
}
@BeanProperty 这个注解会为我们生成java格式的set/get方法和scala格式的get/set 方法, 并且将该字段属性标记为private字段,这也是一种很好的方式,推荐使用
4.IDEA 快捷键生成scala样式的get/set
Alt+Insert
class obb() {
private[this] var _privateAge: Int = 0
def privateAge: Int = _privateAge
def privateAge_=(value: Int): Unit = {
_privateAge = value
}
}
object obb {
def main(args: Array[String]): Unit = {
val o= new obb()
println(o.privateAge)
o.privateAge = 99
print(o.privateAge)
}
这种方式其实和第一种是一样的,不过省事了,不需要字节写代码,idea会自动帮我们生成.