7 scala的类构造器

在创建对象的时候,需要调用类的构造器。Scala 提供了主构造器和辅助构造器。

1 主构造器

与 Java 一样,如果我们没有特别定义,那么 Scala 提供的默认构造器是没有参数的。

我们可以在类名后,指定构造器的参数列表,列表里的参数将成为类的成员属性,这样的构造器叫做主构造器。定义的语法如下:

scala 复制代码
class 类名(var/val 参数名: 参数类型 = 默认值, var/val 参数名: 参数类型 = 默认值 ...) {
	// 构造器代码
}

下面的例子中,我们在主构造器中定义了 name, age, club 三个参数:

scala 复制代码
class FootballPlayer(name: String, age: Int = 20, club: String = "FIFA") {
  var price: Double = 100_0000

  def hello(): String = {
    s"${this.name} is in ${this.club}, ${this.age} years old. Pay ${this.price} dollar to purchase him."
  }
}

object App {
  def main(args: Array[String]): Unit = {
    val footBallPlayer = new FootballPlayer("Cristiano Ronaldo", 39, "Al-Nassr FC")
    println(footBallPlayer.hello())
  }
}

运行后,控制台输出:

markdown 复制代码
Cristiano Ronaldo is in Al-Nassr FC, 39 years old. Pay 1000000.0 dollar if you want to purchase him.

2 辅助构造器

如果需要使用多种方式创建对象,可以使用辅助构造器。定义辅助构造器和定义方法类似,通过关键字 def 定义,不同的是,这个方法的名称固定为 this,语法如下:

scala 复制代码
def this(参数名: 参数类型, 参数名: 参数类型, ...) {
	// 构造器代码
}

例如:

scala 复制代码
/**
 * 球员信息类
 *
 * @param name 球员姓名
 * @param age  年龄
 * @param club 所在俱乐部
 */
class FootballPlayer(name: String, age: Int = 20, club: String = "FIFA") {
  /**
   * 身价
   */
  var price: Double = 100_0000

  /**
   * 辅助构造器
   *
   * @param name  球员姓名
   * @param age   年龄
   * @param club  所在俱乐部
   * @param price 身价
   */
  def this(name: String, age: Int, club: String, price: Double) = {
    // 调用主构造器
    this(name, age, club)
    this.price = price
  }

  def hello(): String = {
    s"${this.name} is in ${this.club}, ${this.age} years old. Pay ${this.price} dollar to purchase him."
  }
}

object App {
  def main(args: Array[String]): Unit = {
    val footBallPlayer = new FootballPlayer("Cristiano Ronaldo", 39, "Al-Nassr FC", 1200_0000)
    println(footBallPlayer.hello())
  }
}
相关推荐
Hanniel3 分钟前
装饰器 (中): 进阶篇,解锁框架级玩法
开发语言·python
pe7er12 分钟前
软件设计不要“既要又要”
前端·后端·架构
柏舟飞流15 分钟前
Spring Boot 深入实践指南:从入门到工程化落地
spring boot·后端·firefox
于先生吖23 分钟前
前后端分离人事招聘项目,校招宣讲预约+社招双向撮合功能架构设计教程
java·开发语言·uni-app
IT_陈寒36 分钟前
Java Stream并行流的坑:我花了3小时才找到的线程安全问题
前端·人工智能·后端
川冰ICE38 分钟前
JavaScript进阶④|Symbol与元编程,对象的隐藏身份
开发语言·javascript·ecmascript
码界索隆38 分钟前
Python转Java系列:作者有话说
java·开发语言·python
橘子海全栈攻城狮42 分钟前
【最新源码】鸟博士微信小程序 023
spring boot·后端·web安全·微信小程序·小程序
Hiter_John1 小时前
Golang的运算符
开发语言·后端·golang
皮皮林5511 小时前
Dubbo 的 SPI 和 JDK 的 SPI 有什么区别?
后端