class Counter {
private var value = 0
def increment(): Unit = {
if (value != Int.MaxValue) value += 1
}
def current(): Int = value
}
val a = new Counter
a.increment()
a.current()
classPerson(var x: Int){privatevar privateAge = if (x < 0) 0else x
def age = privateAge
def age_=(newValue: Int): Unit = {
if (newValue > privateAge) privateAge = newValue
}
}
val Alice = new Person(-2)
Alice.age //res2: Int = 0
//这里惊讶的发现String中间竟然可以放空格classNewPerson(var name: String) {val tokens = name.split("\\s+")
val firstName = tokens(0)
val lastName = tokens(1)
}
val Bob = new NewPerson("Bob Smith")
Bob.firstName //res3: String = Bob
Bob.lastName //res4: String = Smith
5.1 改进5.1节的Counter类,让它不要在Int.MaxValue时变成负数class Counter { private var value = 0 def increment(): Unit = { if (value != Int.MaxValue) value += 1 } def current(): Int = value}val a = ...