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())
  }
}
相关推荐
C嘎嘎嵌入式开发2 小时前
(2)100天python从入门到拿捏
开发语言·python
Stanford_11063 小时前
如何利用Python进行数据分析与可视化的具体操作指南
开发语言·c++·python·微信小程序·微信公众平台·twitter·微信开放平台
Vallelonga4 小时前
Rust 中的数组和数组切片引用
开发语言·rust
Kiri霧4 小时前
Rust模式匹配详解
开发语言·windows·rust
white-persist4 小时前
Python实例方法与Python类的构造方法全解析
开发语言·前端·python·原型模式
千里马-horse4 小时前
Async++ 源码分析8--partitioner.h
开发语言·c++·async++·partitioner
Lucis__5 小时前
再探类&对象——C++入门进阶
开发语言·c++
007php0075 小时前
某大厂跳动面试:计算机网络相关问题解析与总结
java·开发语言·学习·计算机网络·mysql·面试·职场和发展
你的人类朋友5 小时前
先用js快速开发,后续引入ts是否是一个好的实践?
前端·javascript·后端
码事漫谈6 小时前
医疗设备控制系统中同步与异步通信的架构设计
后端