I am start working on existing Scala and Akka project. I say Scala classes, some fields making them as private and providing getter and setter methods in different way. why like that you can make it as public also right.
I say in my project
Why this way:
class Person() {
// Private age variable, renamed to _age
private var _age = 0
var name = ""
// Getter
def age = _age
// Setter
def age_= (value:Int):Unit = _age = value
}
So you can get same feeling like public:
person.age = 99
Why not this simple way?
class Person() {
var name = ""
var age = 0
}
// Instantiate a person object
person = new Person()
// Print the object's age and name properties
println(person.age)
println(person.name)
// Set the properties to different values
person.age = 34
person.name = "Dustin Martin"
答案 0 :(得分:3)
对于这个特定情况,没有理由。如果它来自一个真实的项目,这可能是由一个不了解其观点的人从一个例子中复制而来的。您只想在Scala执行 other 时使用显式的getter / setter方法,而不仅仅是改变私有变量。
(正如Dima的答案正确地说,你应该首先尝试不要var
。)
答案 1 :(得分:2)
两种方式都很糟糕。避免在类中使用可变成员,除非您在特定情况下有特定的理由使用它们。
case class Person(name: String, age: Int) {
def rename(newName: String) = copy(newName)
def grow(numYears: Int) = copy(age = this.age + numYears)
}
val teen = Person("John", 15)
val adult = teen.grow(5)
等
答案 2 :(得分:1)
Accessing and mutating data members of the class directly is the bad idea. Thats why its a good practice to to declare the mutable data member as private
and provide public getter and setter to access and mutate it (data member).
1) Its a good practice because access to the mutable state should be controlled
2) You can add some validation in the getter and setter like this
for getter
def age = if (_age >= 18) _age else throw new Exception("minor")
for setter
def age_=(age: Int) = if (age < 18) throw new Exception("minor") else _age = age
答案 3 :(得分:0)
它主要谈论封装。根据Object world, 你应该只通过一个动作来实现一个状态 。例如,我不能在没有推动加速器的情况下用我的车达到100kmph。因此通过加速(动作)实现车速100kmph(状态)仅。
scala风格的getter和setter可能会给你带来很少的混淆,但这就是所有的语法混淆(在最初几天)但 Scala 没有妥协封装 即可。你仍然可以使用java风格的getter和setters,如下所示
$input = [];
$query = "SELECT * FROM `categories`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$input[] = $row;
}
$result = appendChildren($input);
foreach($result as $row)
{
// open <li> tag
if(count($row["children"]) > 0)
{
foreach($children as $child)
// add ordered list
}
// close <li> tag
}
getter和setter的Java Bean样式将动态生成。但@BeanProperty用于Java互操作性。For more info