var
class Person(var firstName: String, var lastName: String)
public class Person {
private String firstName;
private String lastName;
public String firstName();
public void firstName_$eq(String firstName);
public String lastName();
public void lastName_$eq(String lastName);
public Person(String firstName, String lastName);
}
var
自动生成了「读写」的接口;var
表示可变对象,代表了一种「命令式」的思维;
val
class Person(val firstName: String, val lastName: String)
public class Person {
private final String firstName;
private final String lastName;
public String firstName();
public String lastName();
public Person(String firstName, String lastName);
}
val
只生成了「只读」的接口;val
表示不可变对象,代表了一种「函数式」的思维;val
蕴含了final
的语义;
private
class Person(private val firstName: String, private val lastName: String)
public class Person {
private final String firstName;
private final String lastName;
private String firstName();
private String lastName();
public Person(String firstName, String lastName);
}
Scala
对字段都是private
的,即使没有显式地提供private
;Scala
的private
表示对应的「只读」或「只写」是private
的;
private[this]
Scala
的 private[this]
表示「对象私有性」,类似于Ruby
中的private
;表示只有「本对象」才能访问,就是同类的其他对象也不能访问。
class Person(private[this] var firstName: String, private[this] val lastName: String)
public class Person {
public Person(String firstName, String lastName);
}
当且仅当类中的方法使用了构造器参数,才能自动生成字段;否则仅仅作为主构造器使用的普通函数参数。
class Person(private[this] var firstName: String, private[this] val lastName: String) {
override def toString = s"Person($firstName, $lastName)"
}
public class Person {
private String firstName; // var
private final String lastName; // val
public String toString();
public Person(String firstName, String lastName);
}
无var/val
修饰
工作机制类似于private[this] val
,当且仅当类中的方法使用了构造器参数,才能自动生成字段;否则仅仅作为主构造器使用的普通函数参数。
class Person(firstName: String, lastName: String) {
override def toString = s"Person($firstName, $lastName)"
}
public class Person {
private final String firstName;
private final String lastName;
public String toString();
public Person(String firstName, String lastName);
}
但是,case class
常常使用无var/val
修饰的字段,但它表示val
的语义,而非private[this] val
。
case class Person(name: String)
等价于:
case class Person(val name: String)
@BeanProperty
import scala.beans.BeanProperty
class Person(@BeanProperty var firstName: String)
public class Person {
private String firstName;
public String firstName();
public void firstName_$eq(String firstName);
public void setFirstName(String firstName);
public String getFirstName();
public Person(String firstName);
}
@BooleanBeanProperty
import scala.beans.BooleanBeanProperty
class Person(@BooleanBeanProperty val valid: Boolean)
public class Person {
private final boolean valid;
public boolean valid();
public boolean isValid();
public Person(boolean valid);
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。