Book Image

Professional Scala

By : Mads Hartmann, Ruslan Shevchenko
Book Image

Professional Scala

By: Mads Hartmann, Ruslan Shevchenko

Overview of this book

This book teaches you how to build and contribute to Scala programs, recognizing common patterns and techniques used with the language. You’ll learn how to write concise, functional code with Scala. After an introduction to core concepts, syntax, and writing example applications with scalac, you’ll learn about the Scala Collections API and how the language handles type safety via static types out-of-the-box. You’ll then learn about advanced functional programming patterns, and how you can write your own Domain Specific Languages (DSLs). By the end of the book, you’ll be equipped with the skills you need to successfully build smart, efficient applications in Scala that can be compiled to the JVM.
Table of Contents (12 chapters)

Objects, Classes, and Traits


Scala is a multiparadigm language, which unites functional and OO programming. Now, we will explore Scala's traditional object-oriented programming facilities: object, classes, and traits.

These facilities are similar in the sense that each one contains some sets of data and methods, but they are different regarding life cycle and instance management:

  • Objects are used when we need a type with one instance (such as singletons)

  • Classes are used when we need to have many instances, which can be created with the help of the new operator

  • Traits are used for mix-ins into other classes

Note that it is not worth navigating through code, as this is exposed in examples.

Object

We have seen an object in the previous chapter. Let's scroll through our codebase and open the file named Main in Lesson 2/3-project:

object Chatbot3 {
val effects = DefaultEffects
def main(args: Array[String]): Unit = {
   ….}
   def createInitMode() = (Bye or CurrentDate or CurrentTime...