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())
  }
}
相关推荐
风象南25 分钟前
Token太贵?我用这个数据格式把上下文窗口扩大2倍
人工智能·后端
Victor35627 分钟前
MongoDB(17)如何在MongoDB中创建集合?
后端
摸鱼的春哥40 分钟前
春哥的Agent通关秘籍13:实现RAG查询
前端·javascript·后端
Victor3561 小时前
MongoDB(16)如何在MongoDB中创建数据库?
后端
勇哥java实战分享10 小时前
程序员的明天:AI 时代下的行业观察与个人思考
后端
掘金码甲哥11 小时前
超性感的轻量级openclaw平替,我来给你打call
后端
用户83562907805114 小时前
无需 Office:Python 批量转换 PPT 为图片
后端·python
啊哈灵机一动14 小时前
使用golang搭建一个nes 模拟器
后端
间彧15 小时前
SpringBoot + ShardingSphere 读写分离实战指南
后端
砍材农夫16 小时前
订单超时
后端