scala 为每一个私有变量提供了getter、setter方法,不用显性的定义:
下面是几种方式:
package scalaLearn
class Counter {
private var mycount = 10 // 默认提供了 getter和 setter方法
private var myname = "Scala"
// 实际上他自动实现了getter setter方法
// 自定义
def count = mycount
def count_=(newCount:Int)={
mycount = newCount
}
def this(mycount:Int){
this() // 必须要显式调用构造方法
this.mycount = mycount
}
def this(myname:String, mycount:Int){
this(mycount)
this.myname = myname
}
}
object Counter{
def main(args: Array[String]): Unit = {
val counter = new Counter()
counter.mycount = 290 // 默认提供了getter setter方法
println("使用默认的getter、setter方法:"+counter.mycount)
counter.count = 250
println("使用自己编写的getter和setter方法:"+ counter.count)
val counter2 = new Counter(150)
println(counter2.mycount)
val counter3 = new Counter("亚瑟", 520)
println("名字:"+counter3.myname+" 计数:"+counter3.mycount)
}
}
还有一种
@BeanProperty
var name = "scala"
这种方式不能加 private 修饰变量。
上面用到了伴生对象,所以可以互相访问私有变量。

本文详细介绍了Scala中如何为私有变量提供getter和setter方法,包括默认实现及自定义方法。通过实例展示了不同构造方法的使用,以及如何通过@BeanProperty注解管理变量。同时,探讨了伴生对象在访问私有变量中的作用。
629

被折叠的 条评论
为什么被折叠?



