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())
  }
}
相关推荐
largecode17 分钟前
如何让电话显示店名?来电显示店铺名称,提升有效接通率
java·开发语言·spring·百度·学习方法·业界资讯·twitter
xuhaoyu_cpp_java17 分钟前
SpringMVC学习(五)
java·开发语言·经验分享·笔记·学习·spring
Aurorar0rua18 分钟前
CS50 x 2024 Notes C -11
c语言·开发语言·学习方法
Dlrb121119 分钟前
C语言-指针
c语言·开发语言
咪的Coding27 分钟前
为什么在 DeepSeek 输入 <think>,它竟吐出别人的“记忆碎片”!?
后端·deepseek
zhangzhi197981559231 分钟前
Agent Skills
开发语言·python
HLAIA光子33 分钟前
这些Spring Boot写法已经过时了!
spring boot·后端
alwaysrun1 小时前
Zig实现Windows下进程监控
后端·编程语言
Nyarlathotep01131 小时前
定时线程池:ScheduledThreadPoolExecutor
java·后端
逍遥德1 小时前
SpringBoot自带TaskScheduler 接口实现定时任务的动态增、删、启、停。
java·spring boot·后端·中间件