CHAPTER 2

image

Basics of Scala

Scala is a multi-paradigm language. This chapter introduces functional programming concepts in tandem with nonfunctional programming concepts. This chapter is aimed at making you comfortable with the building blocks of the Scala language. Before embarking on an in-depth journey of Scala, this chapter introduces the basic concepts of Scala that should give you enough understanding to enable you to write useful programs. To that end, we had to leave out some details. We do cover the detailed explanation in the subsequent chapters.

In Chapter 1 you learned to interact with the REPL by typing in expressions. Essentially, everything in Scala is an expression. Expressions and statements in Scala are the same as in Java. The difference between statements and expressions is that a statement does not return a value, while an expression does. However, you might come across situations where an expression does not return any value. This may sound like we are contradicting ourselves, but let’s clear this up by means of an example. If you type the following expression on REPL, you will clearly see that it returns a value:

val x = 2

The value returned by this expression looks like this, as you can see on the REPL:

x: Int = 2

Here, Int is the data type of the value returned. Now enter the following expression:

val x = println(2)

The output on the REPL looks like this:

2x: Unit = ()

The expression val x = println(2) does not return any value. Nevertheless, the Scala compiler discerns the type of x as a special type in Scala for expressions that do not return value, called Unit. This mechanism of inferring the type of the value from its assignment is called type inference. So everything in Scala is an expression. Understanding this is crucial in understanding how, in functional languages, variables are bound to expressions and keep a single value during their entire lifetime due to the requirements of referential transparency. We will explain this in detail in Chapter 4. We begin this chapter by exploring variables and type hierarchy in Scala. All the other concepts introduced in this chapter such as functions, collections, built-in control structures, and pattern matching leverage on the power of expressions. Functions, collections, and pattern matching are introduced briefly in this chapter. We will describe functions, collections, and pattern matching in detail in the subsequent chapters aimed at each of these concepts.

Variables

In Scala, there are three ways you can define variables: val, var, and lazy val. Scala allows you to decide whether or not a variable is immutable (read-only) when you declare it.

An immutable variable is declared with the keyword val. This means that it is a variable that cannot be changed.We will create a value with the name x and assigned with a literal number 10.

val x= 10

Now when you press Enter, the REPL(R) reads the value definition you entered, (E) evaluates it, and (P) prints it as affirmation. The new value, named x, is now defined and available for use as shown in the following code:

scala> val x = 10
x: Int = 10

The value x is now available for use. Remember that we are using it, not changing it. We use it like so:

x*x
scala> x*x
res0: Int = 100

You can choose to make use of res0 (result) value just like any value you explicitly define:

scala> res0 + 1
res1: Int = 101

You can make use of res1 too, like so:

res0 + res1
scala> res0 +res1
res2: Int = 201

Here the values res0 and res1 are added, resulting in the value 201 being returned and stored in the new value named res2.

Now let’s try to reassign a new value to x like so:

x= 202
scala> x=202
<console>:8: error: reassignment to val
       x=202
        ^

x is declared as val and is an immutable variable so you cannot reassign a new value to x. Now let us declare a mutable variable. A mutable variable is declared with keyword var like:

var y  = 10
scala> var y = 10
y: Int = 10

Now let’s reassign a new value to y, like so:

y = 11
scala> var y = 10
y: Int = 10

You can reassign a new value to y as y is mutable, but you cannot reassign the variable to a different type. In the previous expression, y is assigned an Int type. Let us now assign it to a Double:

y = 10.5
scala> y = 10.5
<console>:8: error: type mismatch;
found   : Double(10.5)
 required: Int
       y = 10.5
           ^

However, defining a variable of type Double and assigning it an Int value will work because Int numbers can be converted to Double numbers automatically:

scala> var z =10.5
z: Double = 10.5
scala> z = 11
z: Double = 11.0

Lazy val variables are calculated once, the first time the variable is accessed. Only vals can be lazy variables. You would use a lazy val if the variable may not be used and the cost of calculating it is very long.

scala> val x = 10e20
x: Double = 1.0E21
scala> val y= 10e30
y: Double = 1.0E31
scala> lazy val z = x*y
z: Double = <lazy>
scala> var x = 10
x: Int = 10

Scala Type Hierarchy

Unlike Java, there are no primitive types in Scala. All data types in Scala are objects that have methods to operate on their data. All Scala’s types, from numbers to collections, exist as part of a type hierarchy. Every class that you define in Scala will also belong to this hierarchy automatically. Figure 2-1 shows the hierarchy of Scala’s core types.

9781484202333_Fig02-01.jpg

Figure 2-1. Scala type hierarchy

We will cover each of these core types shown in Figure 2-1 in this section, except Scala.* ref types. There are several ref types in Scala.*, such as Collection and several others and we will cover these in the subsequent chapters. In this section we will begin our discussion with Any, AnyVal, and AnyRef types, followed by Numeric types, Boolean, Char, Unit, and finally we will explain Nothing and Null.

Any, AnyVal and AnyRef Types

Class Any is the root of the Scala class hierarchy and is an abstract class. Every class in a Scala execution environment inherits directly or indirectly from this class. AnyVal and AnyRef extend Any type. The Any, AnyVal, and AnyRef types are the root of Scala’s type hierarchy. All other types descend from AnyVal and AnyRef. The types that extend AnyVal are known as value types. For example, as you will see in numeric types in this section, Double is an abstract final class that extends AnyVal and the types that extend AnyRef are known as reference types (i.e., nonvalue Scala classes and user-defined) classes.

Numeric Types

The numeric data types in Scala constitute Float and Double types along with Integral data types such as Byte, Short, Int, Long, and Char.

Table 2-1 displays Scala’s numeric data types.

Table 2-1. Scala's Numeric Data Types

Data type

Description

Byte

Integers in the range from −128 to 127

Short

Integers in the range from −32768 to 32767

Int

Integers in the range from −2147483648 to 2147483647

Long

Integers in the range from −9223372036854775808 to 9223372036854775807

Float

The largest positive finite float is 3.4028235×1038 and thesmallest positive finite nonzero float is 1.40×10−45

Double

The largest positive finite double is 1.7976931348623157×10308 and the smallest positive finite nonzero double is 4.9×10−324

Scala supports the ability to automatically convert numbers from one type to another in the order Byte image Short image Int image Long image Float image Double.

where the Byte type is the lowest and can be converted to any other type as illustrated in the following example:

scala> val x: Byte = 30
x: Byte = 30

You can assign x to a Short type as illustrated in the following example:

scala> val y: Short = x
y: Short = 30

Likewise you can assign x to an Int, Long, Float, Double, and Scala will automatically convert the numbers for you as illustrated in the following example:

scala> val z: Double = y
z: Double = 10.0

Scala does not allow automatic conversion in the order reverse from mentioned earlier. For example Scala will automatically convert a Long to a Float and Double but not from Long to an Int as illustrated in the following example:

scala> val x: Long = 10
x: Long = 10
scala> val y: Int = x
<console>:8: error: type mismatch;
 found   : Long
 required: Int
val y: Int = x

Boolean Type

The Boolean type is limited to the literal true or the literal false as illustrated in the following example on REPL:

scala> val x = !false
x: Boolean = true

As you can see, Scala discerns the type of x as Boolean.

Char Type

Char literals are written with single-quotes, distinguishing them from String literals, which are written with double quotes as you will see in the following section. The following example illustrates the Char type:

scala> val x = 'X'
x: Char =  X

Unit type

The Unit type is used to define a function that doesn’t return data. It is similiar to the void keyword in Java. We have introduced Unit type in Chapter 1. We insert the code again here for quick reference in Listing 2-1.

Listing 2-1. Main Method with Unit Type

def main(args: Array[String]) : Unit = {
                       }

The Unit literal is an empty pair of parentheses, () as illustrated in the following example.

scala> val empty = ()
empty: Unit = ()

Nothing and Null Types

Nothing and Null types are at the bottom of the Scala type hierarchy shown in Figure 2-1 Null is a subtype of all reference types that is, it is a subtype of all AnyRef types that exist to provide a type for the keyword null. Scala does not have a null keyword. But why Scala even has Null type you ask. This will be explained later in this book as it involves few other concepts that cannot be introduced at this point. Because Null is not a subtype of value types, that is, subtype of AnyVal, null is not a member of any such type. For instance, it is not possible to assign null to a variable of type scala.Int.

Nothing is a subtype of every other type to provide a compatible return type for operations that affect a program’s flow. One of the usages of Nothing is that it signals abnormal termination. Nothing is a trait that is guaranteed to have zero instances. It provides a return type for methods that never return normally (i.e., a method that always throws an exception). You will see one example of Nothing later in this book.

In best practiced Scala, you never use null values. If you’re coming from a language like Java, any time you feel like using a null, use an Option instead. This will be explained in Chapter 6 and Chapter 13.

This concludes the core types in Scala hierarchy. If you have a keen eye, you must have noticed that String type was not discussed in this section. This is because String type in Scala is built on the String type of Java. Now we will briefly introduce how strings are used in Scala.

Strings

Scala’s String is built on Java’s String and adds additional features such as string interpolation to Java’s String.

Following example illustrates a string literal using double quotes:

scala> val hello = "Hello"
hello: String = Hello

String Interpolation

String interpolation is a mechanism to combine your values inside a string with variables. The notation for interpolation in Scala is an s prefix added before the first double quote of the string. Then dollar sign operator $ can be used to reference the variable.

Listing 2-2 illustrates the usageof string interpolation.

Listing 2-2. String Interpolation

val bookTitle = "Beginning Scala" // creating a String
s"Book Title is ${ bookTitle}" // String interpolation

You can try this code on REPL as shown:

scala> val bookTitle = "Beginning Scala"
bookTitle: String = Beginning Scala
scala> s"Book Title is ${ bookTitle}"
res0: String = Book Title is Beginning Scala

Functions

Scala has both functions and methods. A Scala method is a part of a class that has a name and a signature, whereas a function in Scala is a complete object that can be assigned to a variable. A function definition can appear anywhere in a source file.

Function without Parameter

To define a function in Scala, use the def keyword followed by the method name and the method body as shown in Listing 2-3.

Listing 2-3. hello Function

def hello() = {"Hello World!"}

The equal sign = is used as a separator between the method signature and the method body.

Here is the output:

scala> def hello() = {"Hello World!"}
hello: ()String

You can invoke this function using either hello() or hello.

In the preceding method definition you can also include the optional return type as shown in Listing 2-4.

Listing 2-4. Optional Return Type in the Method Definition

def hello():String = {"Hello World!"}
">scala> def hello():String = {"Hello World!"}
hello: ()String

You can invoke this function using either hello() or hello.

It is also possible to remove the parentheses from the method body altogether as shown in Listing 2-5.

Listing 2-5. Method Body Without the Parentheses

def hello() = "Hello World!"
scala> def hello() = "Hello World!"
hello: ()String

You can invoke this function using either hello() orhello.

You can also remove the parentheses from the method signature altogether as shown in Listing 2-6.

Listing 2-6. Method Signature Without Parentheses


def hello = "Hello World!"
scala> def hello = "Hello World!"
hello: String

Function with Parameters

Now you will look at the function involving parameters as shown in Listing 2-7.

Listing 2-7. Function with Parameter

def square (i:Int) = {i*i}

The body of the functions are expressions, where the final line becomes the return value of the function.

scala> def square (i:Int) = {i*i}
square: (i: Int)Int

You can invoke this function as square(2).

You can provide multiple parameters in a function. Multiple parameters are separated by commas as illustrated in Listing 2-8.

Listing 2-8. Function with Multiple Parameters

def add(x: Int, y: Int): Int = { x + y }

You can now invoke this function by passing actual parameters to the add function as shown in the following example on the REPL :

scala> def add(x: Int, y: Int): Int = { x + y }
add: (x: Int, y: Int)Int
scala> add(5, 5)
res0: Int = 10

This concludes the brief introduction to Scala functions. We will describe functions in detail in Chapter 4. Now we will introduce arrays, lists, ranges, and tuples.

Arrays, Lists, Ranges, and Tuples

Next we introduce arrays, lists, ranges and tuples so that you can use them for subsequent sections of this chapter. We will explain lists in detail in Chapter 6.

Arrays

The array is a common data structure consisting of a collection of elements of the same type. Elements are associated with an index, usually an integer, which is used to access or replace a particular element.

Basically, there are two ways to define an array: either you can specify the total number of elements and then assigns values to the elements, or you can specify all values at once.

For example books is declared as an array of Strings that may hold up to three elements as shown in Listing 2-9.

Listing 2-9. Array of Strings

var books:Array[String] = new Array[String](3)
Try Listing 2-9 on REPL as shown:
scala> var books:Array[String] = new Array[String](3)
books: Array[String] = Array(null, null, null)
scala>

Here books is declared as an array of Strings that may hold up to three elements. You can simplify the declaration as shown in Listing 2-10:

Listing 2-10. Simplifying Array Declarations

var books = new Array[String](3)
scala> var books = new Array[String](3)
books: Array[String] = Array(null, null, null)
scala>

You can also define the books array as shown in Listing 2-11.

Listing 2-11. Another Way of Array Declaration

var books = Array("Beginning Scala", "Beginning Java", "Beginning Groovy")

You can assign values to individual elements or get access to individual elements, using commands as illustrated in Listing 2-12:

Listing 2-12. Assigning Values or Accessing Individual Elements

books(0) = "Beginning Scala"; books(1) = "Beginning Java"; books(2) = "Beginning Groovy"
println(books(0))

The index of the first element of an array is the number 0 and the index of the last element is the total number of elements minus one.

Lists

In Scala Lists, all elements have the same type like arrays, but unlike arrays, elements of a list cannot by changed by assignment. The list that has elements of type T is written as List[T]. Types in Scala deserve a chapter of their own and will be discussed in detail in Chapter 8. There are two ways to create a list: either you can create the list in the similar manner you create arrays or you can use :: cons operator. We will show you both the ways of creating lists.

First we will show the more traditional approach. Listing 2-13 shows how you can create an empty list.

Listing 2-13. Creating an Empty List

val empty: List[Nothing] = List()
scala> val empty: List[Nothing] = List()
empty: List[Nothing] = List()
scala>

Note that the type of the list is Nothing.

You can create the list of books as shown in Listing 2-14:

Listing 2-14. Creating a List of Books

val books: List[String] = List("Beginning Scala", "Beginning Groovy", "Beginning Java")

Both these lists can be defined using a tail Nil and ::. Nil also represents the empty list. Differences between Nothing and Nil will be described in Chapter 13. An empty list can be defined using Nil as shown in Listing 2-15:

Listing 2-15. An Empty List Using Nil

val empty = Nil

Nil in Listing 2-15 is known as the tail of the list.

scala> val empty = Nil
empty: scala.collection.immutable.Nil.type = List()

The books list can be defined using a tail Nil and :: as illustrated in Listing 2-16.

Listing 2-16. Creating a List of Books Using a Tail Nill and ::

val books = " Beginning Scala" :: ("Beginning Groovy" :: ("Beginning Java" :: Nil))
scala> val books = " Beginning Scala" :: ("Beginning Groovy" :: ("Beginning Java" :: Nil))
books: List[String] = List(" Beginning Scala", Beginning Groovy, Beginning Java)
scala>

The operations on the lists can be expressed in terms of head and tail methods, where head returns the first element of a list and tail returns a list consisting of all elements except the first element.

scala> books.head
res0: String = " Beginning Scala"
scala> books.tail
res1: List[String] = List(Beginning Groovy, Beginning Java)
scala>

Ranges

Ranges can be defined by their start, their end, and the stepping value.

To create a range in Scala, use the predefined the method to as illustrated in the Listing 2-17:

Listing 2-17. Creating Range Using the Method to

1 to 5
Try Listing 2-17 on REPL as shown.
scala> 1 to 5
res0: scala.collection.immutable.Range.Inclusive = Range(1, 2, 3, 4, 5)
scala>

You can also create a range with the upper limit exclusive of its upper limit using the predefined method until as shown in the Listing 2-18.

Listing 2-18. Creating a Range Using the Until Method

1 until 5

Try Listing 2-18 on REPL as shown:

scala> 1 until 5
res1: scala.collection.immutable.Range = Range(1, 2, 3, 4)
scala>

Note that for 1 to 5, a Range(1,2,3,4,5) is created, but for 1 until 5 a Range with upper limit exclusive Range(1,2,3,4) is created.

You can also create a Range with stepping values using the predefined method by as shown in Listing 2-19.

Listing 2-19. Creating a Range Using the Method By

1 to 20 by 4
scala> 1 to 20 by 4
res2: scala.collection.immutable.Range = Range(1, 5, 9, 13, 17)
scala>

Tuples

A tuple is an ordered container of two or more values of same or different types. Unlike lists and arrays, however, there is no way to iterate through elements in a tuple. Its purpose is only as a container for more than one value. Tuples are useful when you need to group discrete elements and provide a generic means to structure data. You can create a tuple in two ways:

  • By writing your values separated by a comma and surrounded by a pair of parentheses
  • By using a relation operator (->)

Listing 2-20 shows a tuple containing an Int, a Boolean, and a String using the former method.

Listing 2-20. Tuple Using Values Separated by a Comma and Surrounded by a Pair of Parentheses

val tuple = (1, false, "Scala")

If you try Listing 2-20 on REPL, you will see the diverse types of elements contained in the tuple:

scala> val tuple = (1, false, "Scala")
tuple: (Int, Boolean, String) = (1,false,Scala)

Listing 2-21 shows a tuple created using a relation operator:

Listing 2-21. Tuple Using Relation Operator

val tuple2 ="title" -> "Beginning Scala"
scala> val tuple2 ="title" -> "Beginning Scala"
tuple2: (String, String) = (title,Beginning Scala)

Individual elements of a tuple can be accessed by its index, where the first element has an index 1. Listing 2-22 shows accessing the third element of the tuple.

Listing 2-22. Accessing an Element of the Tuple Using Index

val third = tuple._3
scala> val third = tuple._3
third: String = Scala

Built-in Control Structures

The Scala built-in control structures are if, while, for, try, and match expressions. Scala’s built-in control structures are sufficient to provide features that their imperative equivalents provide, but because all of Scala’s control structures (except while loops) result in some value, these control structures support functional approach as well. We will explain this in detail in Chapter 4.

If Expressions

The result of if expressions in Scala is always Unit. The result of if/else is based on the type of each part of the expression. Listing 2-23 illustrates if expressions in Scala.

Listing 2-23. If Expression in Scala

if (exp) println("yes")

Listing 2-23 prints “yes” if exp is true. Like Java, an if expression may have a multiline code block as illustrated in Listing 2-24.

Listing 2-24. Multiline If Expression

if (exp) {
println("Line one")
println("Line two")
}

The if/else in Scala behaves like the ternary operator in Java:

val i: Int = if (exp) 1 else 3

and either (or both) parts of the expression may have multiline code blocks as illustrated in Listing 2-25.

Listing 2-25. Multiline Else

val i: Int = if (exp) 1
else {
val j = System.currentTimeMillis
(j % 100L).toInt
}

While Loops

The while and dowhile constructs are called loops, not expressions, because they don’t result in any values. The type of the result is Unit. while is used very rarely in Scala code. It turns out that a value (and in fact, only one value) exists whose type is Unit.

while executes its code block as long as its expression evaluates to true, just like Java. In practice, using recursion (a method calling itself) provides more readable code and enforces the concept of transforming input to output rather than changing, mutating, variables. Listing 2-26 shows the while loop construct.

Listing 2-26. While Loop

while (exp) println("Working...")
while (exp) {
println("Working...")
}

For Comprehension

A For Comprehension is a very powerful control structure of Scala language. Not only does it offer the ability to iterate over a collection, but also provides filtering options and the ability to generate new collections.

Basic for Expression

This is a very basic feature of the for expression. First we need a collection over which the for expression will iterate. We create a list of books as shown in Listing 2-27:

Listing 2-27. A Book Ccollection

 val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in easy steps", "Scala in 24 hours")

As you can see on REPL, the type of the books list is List[String].

scala> val books = List("Beginning Scala", "Beginning Groovy", "Beginning Java", "Scala in easy steps", "Scala in 24 hours")
books: List[String] = List(Beginning Scala, Beginning Groovy, Beginning Java, Scala in easy steps, Scala in 24 hours)

Now we can write a very basic for expression to iterate over the books list as shown in Listing 2-28.

Listing 2-28. Basic for Expression

for (book<-books)
println(book)

In Line 1 of Listing 2-28, the for expression creates a temporary variable called book for each element in the list books with the corresponding value of that element. The left-arrow operator is called a generator because it generates corresponding values from a collection to be used in an expression.

Here is the output:

scala> for (book<-books)
     | println(book)
Beginning Scala
Beginning Groovy
Beginning Java
Scala in easy steps
Scala in 24 hours

Filters

A filter is an if clause inside the for expression that is used to filter the collection when you do not want to iterate through the entire collection.

So you can find all Scala books in our list of books as illustrated in Listing 2-29.

Listing 2-29. Using Filter

for(book<-books
 if book.contains("Scala")
 ) println(book)

Here is the output:

scala> for(book<-books
     | if book.contains("Scala")
     | ) println(book)
Beginning Scala
Scala in easy steps
Scala in 24 hours

Variable Binding

You can define variables inside for expressions. You can then re-use these variables within the body of your for expression as illustrated in Listing 2-30.

Listing 2-30. Variable Binding in For Comprehension

 for {book <- books
 bookVal = book.toUpperCase()
} println(bookVal)

Note that bookVal is not declared as a val, but you can still reuse it. This proves to be very useful in situations where you want to transform the elements in your collection while looping through them such as when we transform each book in the books list to uppercase.

Yielding

In Scala’s for expression you can use the yield keyword to generate new collections.

The type of the collection generated from the for expression is inferred from the type of the collection being iterated over. We show the example of yielding a collection in Listing 2-31.

Listing 2-31. Using Yield in for Comprehension

var scalabooks = for{
book <-books
if  book.contains("Scala")
}yield book
scala> var scalabooks = for{
     | book <-books
     | if  book.contains("Scala")
     | }yield book
scalabooks: List[String] = List(Beginning Scala, Scala in easy steps, Scala in 24 hours)

The filtered result is yielded as a value named book. This result is accumulated with every run inside the for loop, and thus accumulated collection is assigned to the value scalabooks.

The scalabooks is of type List[String], because it is a subset of the books list, which is also of type List[String].

try expressions

Exception handling in Scala is implemented differently, but it behaves exactly like Java and works seamlessly with existing Java libraries. All exceptions in Scala are unchecked; there is no concept of checked exception. Scala facilitates a great deal of flexibility in terms of the ability to choose whether to catch an exception.

Throwing exceptions is the same in Scala and Java as shown in Listing 2-32.

Listing 2-32. Throwing Exception

throw new Exception("some exception...")

The try/finally construct is also the same in Scala and Java as shown in Listing 2-33.

Listing 2-33. try/finally in Scala

try {
throw newException("some exception...")
} finally{
println("This will always be printed")
}

The try/catch construct is different in Scala than in Java, in that, try/catch in Scala is an expression that results in a value and that the exception in Scala can be pattern matched in the catch block instead of providing a separate catch clause for each different exception. Because try/catch in Scala is an expression, it becomes possible to wrap a call in a try/catch and assign a default value if the call fails. Listing 2-34 shows a basic try/catch expression with pattern matched catch block.

Listing 2-34. try/catch in Scala

try {
file.write(stuff)
} catch{
case e:java.io.IOException => // handle IO Exception
case n:NullPointerException => // handle null pointer
}

Listing 2-35 shows an example of wrapping a call in try/catch by calling Integer.parseInt and assigning a default if the call fails.

Listing 2-35. Wrapping a Call in try/catch and Assigning a Default if the Call Fails

scala> try{Integer.parseInt("dog")}catch{case_ => 0}
res16:Int = 0

You can see in Listing 2-35, calling Integer.parseInt and defaulting to 0 if an exception is thrown. You can see the output in Listing 2-36 when the call Integer.parseInt does not fail.

Listing 2-36. When the Call Does not Fail

scala> try{Integer.parseInt("44")} catch{case _ => 0}
res17:Int = 44

Match Expressions

Scala’s match expressions are used for pattern matching by allowing you to construct complex tests in very little code and are extremely flexible constructs that enable matching arbitrary items, such as types, content of the data structure, regular expressions, and even ranges of numeric types. Pattern matching is like Java’s switch statement, but you can test against almost anything, and you can even assign pieces of the matched value to variables. Like everything in Scala, pattern matching is an expression, so it results in a value that may be assigned or returned. The most basic pattern matching is like Java’s switch, except there is no break in each case as the cases do not fall through to each other. Listing 2-37 matches the number against a constant, but with a default.

Listing 2-37. Using Match Expression

44 match {
case 44 => true// if wematch 44,theresult is true
case _ => false// otherwisetheresult isfalse
}

Like C#, you can match against a String as shown in Listing 2-38.

Listing 2-38. Matching Against a String


"David"match {
case "David"=> 45 // the result is 45 if we match "David"
case "Elwood" => 77
case _ => 0
}

We will explain pattern matching in detail in Chapter 5.

Comments

Scala comments are much like Java and C++ comments. Multiline comments start with /* and ended with */.

/*
This is a multiline comment:
*/

A single-line comment is started with // and continues to the end of the line:

// This is a single line comment

In Scala, you can nest multiline comments:

/*
This is an outer comment
/* And this comment
is nested
*/
Outer comment
*/

Summary

We’ve covered a lot of ground in this chapter. We did an overview of Scala’s syntax and basic constructs. Some of the concepts in this chapter, such as pattern matching and for comprehensions, are functional programming concepts. But because Scala is a multi-paradigm language, we included them with the rest of the nonfunctional programming concepts and will be described in detail in later chapters. In the next chapter, we’re going to explore object orientated programming in Scala.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset