Scala Constructors and Auxiliary Constructors

本文深入探讨Scala中的构造器概念,包括基本构造器的功能及其初始化过程,并通过实例展示辅助构造器的使用方法,以及如何实现构造器重载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原创转载请注明出处:http://agilestyle.iteye.com/blog/2333245

 

Constructors

The constructor is the code that "constructs" a new object. The constructor is the combined effect of the class argument list - initialized before entering the class body - and the class body, whose statements execute from top to bottom.

The simplest form of a constructor is a single line class definition, with no class arguments and no executable lines of code, such as:

class Person

In Fields, the constructor initializes the fields to the values specified, or to defaults if no values were specified. In Class Arguments, the constructor quietly initializes the arguments and makes them accessible to other objects; it also unravels a variable argument list.

In those cases, we didn’t write constructor code – Scala did it for us. For more customization, add your own constructor code. For example: 

package org.fool.scala.constructors

class Coffee(val shots: Int = 2,
             val decaf: Boolean = false,
             val milk: Boolean = false,
             val toGo: Boolean = false,
             val syrup: String = "") {
  var result = ""
  println(shots, decaf, milk, toGo, syrup)

  def getCup(): Unit = {
    if (toGo)
      result += "ToGoCup "
    else
      result += "HereCup "
  }

  def pourShots(): Unit = {
    for (s <- 0 until shots)
      if (decaf)
        result += "decaf shot "
      else
        result += "shot "
  }

  def addMilk(): Unit = {
    if (milk)
      result += "milk "
  }

  def addSyrup(): Unit = {
    result += syrup
  }

  getCup()
  pourShots()
  addMilk()
  addSyrup()
}

object ConstructorsTest extends App {
  val usual = new Coffee()
  println(usual.result)

  val mocha = new Coffee(decaf = true, toGo = true, syrup = "Chocolate")
  println(mocha.result)
}

Console Output

 

Auxiliary Constructors

Named and default arguments in the class argument list can construct objects in multiple ways. We can also use constructor overloading by creating multiple constructors. The name is overloaded here because you’re making different ways to create objects of the same class. To create an overloaded constructor you define a method (with a distinct argument list) called this (a keyword). Overloaded constructors have a special name in Scala: auxiliary constructors.

Because constructors are responsible for the important act of initialization, constructor overloading has an additional constraint: all auxiliary constructors must first call the primary constructor. This is the constructor produced by the class argument list together with the class body. To call the primary constructor within an auxiliary constructor, you don’t use the class name, but instead the this keyword:

package org.fool.scala.constructors

class GardenGnome(val height: Double,
                  val weight: Double,
                  val happy: Boolean) {
  println("Inside primary constructor...")
  var painted = true

  def magic(level: Int): String = "Poof! " + level

  def this(height: Double) {
    this(height, 100.0, true)
  }

  def this(name: String) = {
    this(15.0)
    painted = false
  }

  def show(): String = height + " " + weight + " " + happy + " " + painted
}

object AuxiliaryConstructorsTest extends App {
  val g1 = new GardenGnome(20.0, 110.0, false)
  println(g1.show())
  println(g1.magic(1))

  println(new GardenGnome("MyGarden").show())
  println(new GardenGnome("MyGarden").magic(2))
}

Console Output


  

 

Reference

Atomic Scala 2nd Edition - Construtors

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值