2

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

  • Scalaprivate表示对应的「只读」或「只写」是private的;

private[this]

Scalaprivate[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);
}

horance
255 声望29 粉丝

刘光聪,程序员,敏捷教练,开源软件爱好者,具有多年大型遗留系统的重构经验,对OO,FP,DSL等领域具有浓厚的兴趣。


引用和评论

0 条评论