`

Scala Constructors and Auxiliary Constructors

 
阅读更多

原创转载请注明出处: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

 

 

  • 大小: 13.9 KB
  • 大小: 17.2 KB
分享到:
评论

相关推荐

    Scala and Spark for Big Data Analytics.pdf

    Spark itself is written with Scala and naturally, as a starting point, we will discuss a brief introduction to Scala, such as the basic aspects of its history, purposes, and how to install Scala on ...

    Reactive.Programming.with.Scala.and.Akka.1783984341.epub

    Harness reactive programming to build scalable and fault-tolerant distributed systems using Scala and Akka About This Book Use the concepts of reactive programming to build distributed systems ...

    Scala and Spark for Big Data Analytics

    Scala and Spark for Big Data Analytics by Md. Rezaul Karim English | 25 July 2017 | ISBN: 1785280848 | ASIN: B072J4L8FQ | 898 Pages | AZW3 | 20.56 MB Harness the power of Scala to program Spark and ...

    scala futures and promises

    ### Scala Futures and Promises 实践入门 #### 凤凰木 #### September 14, 2018 在本文档中,我们将通过一系列实例来探讨Scala中的`Future`和`Promise`的概念,并与Java中的多线程技术进行对比。这些概念是函数式...

    Scala and Spark for Big Data Analytics epub

    Scala and Spark for Big Data Analytics 英文epub 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Programming in Scala

    the new language for the Java Platform that blends object-oriented and functional programming concepts into a unique and powerful tool for developers.Coauthored by the designer of the Scala language,...

    Modern Programming Made Easy Using Java Scala Groovy and JavaScript 无水印pdf

    Modern Programming Made Easy Using Java Scala Groovy and JavaScript 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 ...

    2018 Scala for Java Developers: A Practical Primer

    Learn Scala is split into four parts: a tour of Scala, a comparison between Java and Scala, Scala-specific features and functional programming idioms, and finally a discussion about adopting Scala in...

    Reactive Programming with Scala and Akka mobi

    Reactive Programming with Scala and Akka 英文mobi 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者或csdn删除

    Functional Programming Patterns in Scala and Clojure(Pragmatic,2013)

    Use Scala and Clojure to solve in-depth problems with two sets of patterns: object-oriented patterns that become more concise with functional programming, and natively functional patterns. Your code ...

    functional programming in scala and impatient.pdf

    《Functional Programming in Scala》与《Scala for the Impatient》是两本关于Scala编程语言的重要书籍,专注于函数式编程思想和Scala语言的深入学习。Scala是一种多范式编程语言,结合了面向对象和函数式编程的...

    scala3 scala3 scala3 scala3 scala3

    Scala3,也被称为Scala 3或Dotty,是Scala编程语言的一个重大更新,旨在提高其简洁性、可读性和类型安全性。Scala3的发布标志着该语言的进一步成熟,它引入了一系列改进,旨在解决早期版本中的一些痛点,同时保持对...

    scala sdk scala-2.12.3

    Scala SDK,全称为Scala Software Development Kit,是用于开发Scala应用程序的核心工具集。Scala是一种多范式的编程语言,融合了面向对象和函数式编程的特点,它运行在Java虚拟机(JVM)上,能够充分利用Java生态...

    scala-sbt-scala编译工具

    Supports testing with ScalaCheck, specs, and ScalaTest. JUnit is supported by a plugin. Starts the Scala REPL with project classes and dependencies on the classpath Modularization supported with sub-...

    scala211-eclipse-plugin(4.4and4.5).zip

    这个压缩包"scala211-eclipse-plugin(4.4and4.5).zip"显然是针对Eclipse 4.4 (Luna) 和 4.5 (Mars) 版本设计的,它包含了使 Scala 开发者能够充分利用这两个版本的 Eclipse 的功能。 1. **Scala 语言**: Scala 是一...

    Data Structures and Algorithms with Scala

    《Data Structures and Algorithms with Scala》是一本专注于使用Scala语言探讨数据结构与算法的书籍。Scala是一种多范式编程语言,融合了面向对象和函数式编程的特性,它为理解和实现数据结构与算法提供了独特的...

    scala and lift 4 books

    Scala和Lift是两个在Java平台上非常重要的技术,它们在构建现代、高性能的Web应用程序方面发挥着关键作用。本文将深入探讨这两个主题以及相关的书籍资源。 首先,让我们从Scala开始。Scala是一种多范式编程语言,它...

    Scala for Java Developers(PACKT,2014)

    Scala for Java Developers is a step-by-step guide full of easy-to-follow code taken from real-world examples explaining the migration and integration of Scala in a Java project. With this book, you ...

    Scala语法简明教程

    - Udemy上的《Scala and Akka Microservices》:教授如何使用Scala和Akka框架构建微服务。 - **社区与论坛**: - Scala官方网站([http://www.scala-lang.org](http://www.scala-lang.org/)):提供了大量的文档...

Global site tag (gtag.js) - Google Analytics