Scala

Programming

For Beginners

Learn Coding Fast!

Ray Yao

Copyright © 2015 by Ray Yao

All Rights Reserved

Neither part of this book nor whole of this book may be reproduced or transmitted in any form or by any means electronic, photographic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without prior written permission from the author. All rights reserved!

Ray Yao

Ray Yao’s eBooks & Books on Amazon

Advanced C++ Programming by Ray Yao

Advanced Java Programming by Ray Yao

AngularJs Programming by Ray Yao

C# Programming by Ray Yao

C# Interview & Certification Exam

C++ Programming by Ray Yao

C++ Interview & Certification Exam

Django Programming by Ray Yao

Go Programming by Ray Yao

Html Css Programming by Ray Yao

Html Css Interview & Certification Exam

Java Programming by Ray Yao

Java Interview & Certification Exam

JavaScript Programming by Ray Yao

JavaScript 50 Useful Programs

JavaScript Interview & Certification Exam

JQuery Programming by Ray Yao

JQuery Interview & Certification Exam

Kotlin Programming by Ray Yao

Linux Command Line

Linux Interview & Certification Exam

MySql Programming by Ray Yao

Node.Js Programming by Ray Yao

Php Interview & Certification Exam

Php MySql Programming by Ray Yao

PowerShell Programming by Ray Yao

Python Programming by Ray Yao

Python Interview & Certification Exam

R Programming by Ray Yao

Ruby Programming by Ray Yao

Rust Programming by Ray Yao

Scala Programming by Ray Yao

Shell Scripting Programming by Ray Yao

Visual Basic Programming by Ray Yao

Visual Basic Interview & Certification Exam

Xml Json Programming by Ray Yao

Preface

“Scala Programming” covers all essential Scala language knowledge. You can learn complete primary skills of Scala programming fast and easily.

The book includes more than 60 practical examples for beginners and includes tests & answers for the college exam, the engineer certification exam, and the job interview exam.

Note:

This book is only for Scala beginners, it is not suitable for experienced Scala programmers.

Source Code for Download

This book provides source code for download; you can download the source code for better study, or copy the source code to your favorite editor to test the programs.

Source Code Download Link:

https://forms . aweber . com/form/76/1081568876 . htm

Table of Contents

Hour 1

What is Scala Language?

The Feature of Scala

Install JDK

Install Scala

Hour 2

“Hello World” Program

Basic Grammar

Scala Keywords

Scala Comment

Package

Data Type

Hour 3

Variables

Declare Variable Type

Declare Multi Variables

Constants

Arithmetical Operators

Comparison Operators

Logical Operators

Assignment Operators

Hour 4

If Statement

If-else Statement

If…else if…else

While Loop

Do-While Loop

For Loop (1)

For Loop (2)

For Loop (3)

Hour 5

Method

Default Parameters

Closure

String

String Length

String Connection

String Functions

Hour 6

Array

Access Array Elements

Connect Array

Reverse Array Elements

Array Operations

Array Sort

Hour 7

Scala List

Connect Two Lists

Scala Set

Set Operations

Scala Map

Connect Two Maps

Map Key & Value

Hour 8

Tuple

Tuple Iteration

Scala Iterator

Useful Function in Iterator

Class

Object

Class & Object

Appendix 1

Extends

Private

Protected

Exception

Appendix 2

Tests

Answers

Source Code Download

Hour 1

What is Scala Language?

The Scala language is a general-purpose programming language that can be executed on the JVM and. net platforms for both large-scale application development and lightweight programming. It was developed by Martin Odersk in 2001. Scala is widely used for its elegant type-safe programming scheme.

Scala is a pure object-oriented language with OO features, but it's also a functional language that allows you to write code with functional ideas.

Scala is built on top of the JVM and interoperates seamlessly with Java.

The great advantage of Scala: The Scala language is scalable, allowing you to write both small scripts and complex server-side programs.

The Feature of Scala

Scala is a pure object-oriented programming language

- Encapsulation/information hiding.

- Inheritance.

- Polymorphism/dynamic binding.

- All predefined types are objects.

- All operations are performed by sending messages to objects.

- All user-defined types are objects.

Scala is a functional programming language

- Higher-order functions

- Closures

- Pattern matching

- Single assignment

- Lazy evaluation

- Type inference

- Tail call optimization

- Type inference

Scala is very compatible and portable

- Scala executes on the JVM

- Scala can interoperate with JAVA

- Scala has the same platform portability as JAVA

Install JDK

Before  installing Scala, you must install Java JDK first.

About JDK (also called Java SE)

JDK (Java Development Kit) contains all Java class libraries, all tool building and running Java programs. JDK can create a Java development environment.

Download JDK

http://oracle . com/download

or

http://www . oracle . com/technetwork/java/javase/downloads/index . html

Please click the link to download the newest version JDK at Oracle website. (Figure 1)

(Figure 1   Download JDK at Oracle Website)

If your computer is a 32-bit operating system, download the JDK with x86; If your computer is a 64-bit operating system, download the JDK with x64. (Figure 2)

(Figure 2)

Install the JDK

Please install the newest version of the JDK to your computer. For example, install Java SE 12.0.1.

After installing the Java SE 12. 0. 1, please check the directory:

C:\Program Files\Java\jdk-12. 0. 1

You can find the “jdk-12.0.1 ” in there.

Please remember the installation path and jdk version.

Configure Java Environment Variables

The following chart is the configure parameters:

Variable Name

JAVA_HOME

Variable Value

C:\Program Files\Java\jdk-12 . 0 . 1

Variable Name

Path

Variable Value

; %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin ;

1. Please click  Control Panel > System > Advanced System Settings > Environment Variables

2. Click “ New… ”

3. Input “JAVA_HOME”.

4. Input “C:\Program Files\Java\jdk-12. 0. 1”

As follows:

5. Click “OK ”

6. Select “Path”.

7. Click “Edit… ”

8. Append “ ; %JAVA_HOME%\bin;%JAVA_HOME%\jre\bin; ”

As follows:

( Note: If in Windows 10, you need to add the variable values one by one as follows: )

9. Click “OK ”, and restart the computer.

Test Java Environment

"Start" > " Run" > type "cmd ". Go to “C:\Users\YourName”.

Type “Java  -version ” as follows

Congratulation! The JDK has been installed successfully!

Install Scala

Download the Scala

https://www . scala-lang . org/download/

Click Scala-2.12.8.msi.

Install the Scala

Please install scala-2.12.8 in C:\Program Files (x86)\scala.

And remember the directory:

C:\Program Files (x86)\scala

Configure Scala Environment Variables

The following chart is the configure parameters:

Variable Name

SCALA_HOME

Variable Value

C:\Program Files (x86)\scala

Variable Name

Path

Variable Value

; %SCALA_HOME%\bin;%SCALA_HOME%\jre\bin ;

Variable Name

Classpath

Variable Value

. ; %SCALA_HOME%\bin ;

Note: the method of the configure Scala environment variables is the same as the method of the configure Java environment variables.

Click “New…”

Click “OK” , and restart the computer.

Test Scala Environment

"Start" > " Run" > type "cmd ". Go to “C:\Users\YourName”.

Type “scala  -version ” as follows

Congratulation! The Scala has been installed successfully!

Hour 2

“Hello World” Program

Working Folder

Please go to C:\Users\YourName, create a folder “myScala ”. Now the working folder is “C:\Users\YourName\myScala ”, which is used to save Scala files.

Example 2.1

Please open the Windows NotePad, write the following code in it.

object HelloWorld {

def main(args: Array[String]) {

println("Hello, world! ")

}

}

Save the file as “HelloWorld. scala” in the working folder “myScala”.

"Start" > " Run" > type "cmd ". Go to “C:\Users\YourName\myScala”. Type “scala HelloWorld. scala”, run the program

Output:

Hello world!

Explanation:

“object HelloWorld” means that the object name is “HelloWorld”

Note: The file name of the Scala file should be the same as object name.

The Scala extension name is “. scala”.

The Scala files should be saved in the working folder “myScala”

“def main(args: Array[String])” is the main function that is always executed first.

“args: Array[String]” is the argument which is used to accept the input of the string.

“println( )” outputs the contents.

“scala  HelloWorld. scala” is a command to run the HelloWorld program.

Basic Grammar

- Case-sensitive

Scala is a case-sensitive language.

For example: Hello and hello is different.

- Class name

The first letter of all class names should be capitalized.

For example: HelloWorld

- File name & Object name

The file name should be the same as object name.

For example: HelloWorld. scala  &  object HelloWorld

- Method names

All method names start with a lowercase letter.

For example: def myMethod( )

- Semicolon (;)

A semicolon is used to end a line of statement.

For example: println(“Hello”);

Scala Keywords

Scala keywords are reserved by Scala Language. We cannot use the following keywords as variables, constants, or function names.

abstract

case

catch

class

def

do

else

extends

false

final

finally

for

forSome

if

implicit

import

lazy

match

new

null

object

override

package

private

protected

return

sealed

super

this

throw

trait

try

true

type

val

var

while

with

yield

-

:

=

=>

<-

<:

<%

>:

#

@

Scala Comment

/*….. */  is a symbol for multi-line comment

//   is a symbol for single-line comment

Example 2.2

object HelloWorld {

/*

* Here is a hello-world program

* Here is a Scala program sample

*/

def main(args: Array[String]) {

println("Hello, world! ")    // output Hello, world !

}

}

Output:

Hello, world!

Explanation:

/*…*/ is used for multi-line comments

// is used in single-line comments

Package

A package is a code module that has some functionality, The Scala package provides specific functionality to the program.

Define a package:

package package_name

class class_name

For example:

package myPackage{     // define a package

class HelloWorld     // the content of the package

}

Import a package

import package_name

For example:

import java. awt. Color   // import Color package

Data Type

The data type of the Scala is the same as the data type of the Java.

Data Type

Description

Byte

8-bit signed integer

Short

16-bit signed integer

Int

32-bit signed integer

Long

64-bit signed integer

Float

32-bit floating point number

Double

64-bit floating point number

Char

16-bit unsigned unicode character

String

character series

Boolean

true or false

Unit

no value

Null

empty reference

Nothing

sub class of any other type

Any

super class of any other type

AnyRef

base class for all referenced classes

Int Type

For example:

100

88

Long Type

A long type number is followed by a L.

For example:

0868L

3000L

Float Type

A float type number is followed by an F.

For example:

2c60F

3. 14159F

Boolean Type

For example:

true

false

Character Type

Character types are defined by single quotes ‘ ’.

For example:

‘ a’

‘ B’

String Type

String Types are defined by double quotes “ ”.

For example:

“ Go in 8 Hours”

“ Rust in 8 Hours”

Multi-line String Type

Multi-line String Type are defined by treble quotes “““   ”””.

For example:

“““    Django in 8 Hours

& AngularJS in 8 Hours

are very good books    ”””

Null Type

Null type contains an empty value.

For example:

Scala. Null

Scala. Nothing

Escape Sequences

The “ \ ” backslash character can be used to escape characters.

\n outputs content to the next new line.

\r makes a return

\t makes a tab

\’ outputs a single quotation mark.

\” outputs a double quotation mark.

For example:

println("Hello, \t\t\t World! " )    // Output:  Hello,      Would !

Hour 3

Variables

Variable: the value of which may change while the program is running. The syntax to define a variable is as follows:

var variable_name =  value

Example 3.1

object Var000 {

def main(args: Array[String]) {

var myVar = 100      // define a variable

print(myVar)

}

}

Output:

100

Explanation:

“var myVar = 100” define a variable “myVar”, its value is 100.

Declare Variable Type

The syntax of declaring a variable type is as follows:

var variable     : type = value

Example 3.2

object Var001 {

def main(args: Array[String]){

var myVar1:Int = 1000         // define Int variable

var myVar2:String = " Good "      // define String variable

print(myVar1)

print(myVar2)

}

}

Output:

1000  Good

Explanation:

“var myVar1:Int = 1000” define an Int type variable.

“var myVar2:String = " Good "” define a String variable.

Declare Multi Variables

The syntax to declare multi variables are as follows:

var variable1, variable2, variable3 = value

Example 3.3

object Var002 {

def main(args: Array[String]){

var var1, var2, var3 = 10000;       // define multi variables

println(var1);

println(var2);

println(var3)

}

}

Output:

10000

10000

10000

Explanation:

“var var1, var2, var3 = 10000;” defines multi variables.

Constants

Constant: the value of which cannot change while the program is running. There are two formats to define a constant as follows:

val Constant_Name = value

val Constant_Name     : type =  value

Example 3.4

object Val002 {

def main(args: Array[String]){

val Con1 = "C# in "     // define a constant

val Con2 : Int = 8         // define a constant

val Con3 : String = " Hours"     // define a constant

print(Con1 + Con2 + Con3);

}

}

Output:

C#  in  8 Hours

Explanation:

The first letter of a constant name should be capitalized.

Arithmetical Operators

Operators

Running

+

add or connect strings

-

subtract

*

multiply

/

divide

%

get modulus

% modulus operator divides the first operand by the second operand, returns the remainder. e. g. 4%2, the remainder is 0.

Example 3.5

object Arith000 {

def main(args: Array[String]) {

var add=100 + 200;   println (add);   // output 300

Var div=800 / 2;   println (div);   // output 400

var mod=10 % 3;   println ( mod );    // output 1

}

}

Output:

300

400

1

Explanation:

+

add or connect strings

/

divide

%

get modulus

Comparison Operators

Operators

Running

>

greater than

<

less than

>=

greater than or equal

<=

less than or equal

==

equal

! =

not equal

After using comparison operators, the result will be true or false.

Example 3.6

object com000 {

def main(args: Array[String]) {

var x = 200; var y = 100;

println( x == y );    // output false

println( x ! = y );       //  output true

println( x > y );         //  output true

println( x <= y );     // output false

}

}

Output:

false

true

true

false

Explanation:

>

greater than

<

less than

>=

greater than or equal

<=

less than or equal

==

equal

! =

not equal

Logical Operators

Operators

Equivalent

&&

and

||

or

!

not

After using logical operators, the result will be true or false.

Example 3.7

object log000 {

def main(args: Array[String]) {

var x=true; var y=false;

var a = x && y;   println ( a );

var b = x || y;   println ( b );

var c = ! x;   println ( c );

}

}

Output:

false

true

flase

Explanation:

true && true;

returns true;

true && false;

returns false;

false &&false;

returns false;

true II true;

returns true;

true II false;

returns true;

false II false;

return false;

! false;

returns true;

! true;

returns false;

Assignment Operators

Operators

Examples:

Equivalent:

+=

x+=y

x=x+y

-=

x-=y

x=x-y

*=

x*=y

x=x*y

/=

x/=y

x=x/y

%=

x%=y

x=x%y

Example 3.8

object log000 {

def main(args: Array[String]) {

var x=90;   var y=2;

x+=y;  println ( x );

x/=y;   println ( x );

x%=y;  println ( x );

x-=y;   println ( x );

}

}

Output:

92

46

0

-2

Explanation:

x+=y

is equal to  x=x+y

x-=y

is equal to  x=x-y

x%=y

is equal to  x=x%y

x/=y

is equal to  x=x/y

Hour 4

If Statement

if ( test-expression ) {       // if true do this;    }

“if statement” executes codes inside { … } only if a specified condition is true, does not execute any codes inside {…} if the condition is false.

Example 4.1

object If000 {

def main(args: Array[String]) {

var a=200;

var b=100;

if (a>b) {   // if true, do this

print ( "a is greater than b" );

}

}

}

Output:

a is greater than b

Explanation:

( a>b ) is a test expression, namely (200>100), if returns true, it will execute the codes inside the { }, if returns false, it will not execute the codes  inside the { }.

If-else Statement

if ( test-expression) {   // if true do this;    }

else  {   // if false do this;    }

“if... else statement” runs some code if a condition is true and runs another code if the condition is false

Example 4.2

object Ifelse001 {

def main(args: Array[String]) {

var a=100; var b=200;

if (a>b) {print ("a is greater than b. ")}

else { print ( "a is less than b" );}      // do this

}

}

Output:

a is less than b

Explanation:

( a>b ) is a test expression, namely (100>200), if returns true, it will output  ”a is greater than b. ” if returns false, it will output “a is less than b”.

If…else if…else

“If…else if…else” is a multi-test expression.

if ( test expression ){

//  if true, do this

} else if ( test expression ){

//  if true, do this

} else if ( test expression ){

//  if true, do this

} else {

//  if true, do this

}

Example 4.3

object IfStatement {

def main(args: Array[String]) {

var x = 200;

if ( x == 100 ){

println("The value of x is 100");

}else if ( x == 200 ){    // if true , do this

println("The value of x is 200");

}else if ( x == 300 ){

println("The value of x is 300");

}else {

println("Do know the value of X");

}

}

}

Output:

The value of x is 200

Explanation:

Because the precondition is “var x = 200;”, therefore the “if( x == 200 )” is true, then output the “The value of x is 200”.

While Loop

while ( test-expression ) {      // some code in here;   }

“while loop” loops through a block of code if the specified condition is true.

Example 4.4

object While000 {

def main(args: Array[String]) {

var counter = 0

while (counter < 8) {    // run 8 times

print ( "&" );

counter = counter + 1;

}

}

}

Output:

&&&&&&&&

Explanation:

“counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the counter is 8, then the condition is false, the code will stop running.

Do-While Loop

Do {    // some code in here} while ( test-expression);

“do... while” loops through a block of code once, and then repeats the loop if the specified condition is true.

Example 4.5

object Do000 {

def main(args: Array[String]) {

var counter = 0

do {

print ( "@" );

counter = counter +1;

} while (counter<8);      // run 8 times

}

}

Output:

@@@@@@@@

Explanation:

“counter< 8” is a test expression, if the condition is true, the code will loop less than 8 times, until the counter is 8, then the condition is false, the code will stop running.

For Loop (1)

for( variable <    - number1 to number2) { // some code; }

“for( variable <- number1 to number2){}” runs the code block by the specified number of times from number1 to number 2.

Example 4.6

object For000 {

def main(args: Array[String]) {

var x = 0;

for( x <- 0 to 8) {    // run 8 times

print( x );

}

}

}

Output:

012345678

Explanation:

“for( x <- 0 to 8)” runs the code by the number of times from 0 to 8.

For Loop (2)

for( variable <    - number1 until number2) { // some code; }

“for( variable <- number1 until number2){}” runs the code block by the specified number of times from number1 until number 2.

Example 4.7

object For001 {

def main(args: Array[String]) {

var y = 0;

for( y <- 0 until 8) {   // run 7 times

print( y );

}

}

}

Output :

01234567

Explanation:

“for( x <- 0 until 8)” runs the code by the number of times from 0 until 8.

For Loop (3)

for( variable <    - List) { // some code; }

“for( variable <- List) { // some code; }” runs the block of code based on the values of the List.

Example 4.8

object For002 {

def main(args: Array[String]) {

var z = 0;

val myList = List(0,1,2,3,4,5);

for( z <- myList ){   // run the code based on the List

print( z );

}

}

}

Output:

012345

Explanation:

“for( z <- myList )” runs the code based on the values of the List.

Hour 5

Method

A method is a code block that can repeat to run many times. To define a method.

(1) The syntax to define a method is as follows:

def method_name( )    : return_type={……}

If the method has no return value, the return type can be Unit.

(2)To call a method, use “method_name ( );”

method_name ( );

Example 5.1

object Test {

def main(args: Array[String]) {

println( "The result is : " + mul(50,2) );   // call the method

}

def mul( x:Int, y:Int ) : Int = {   // define a method

var result:Int = 0

result = x * y

return result        // return value

}

}

Output:

The result is : 100

Explanation:

“def mul( x: Int, y: Int ) : Int = { } “ defines a method

“x: Int” specifies that the data type of x is Int.

“”mul(50,2) ); “ calls the method. 50 and 2 are parameters which are passed to x and y.

If the method has no return value, the return type can be specified as Unit , for example:  def method_name( ):Unit ={……}

Default Parameters

When defining a method, you can use the default parameters.

method_name( arg1=value1, arg2=value2)

Example 5.2

object Defa000 {

def main(args: Array[String]) {

println(mul() );   // call the method without parameters

}

def mul( a:Int=100, b:Int=2 ) : Int = {    // default parameters

var result:Int = 0

result = a * b

return result

}

}

Output:

200

Explanation:

“a:Int=100, b:Int=2” are default parameters. When you call a method without using parameters, in this case, the default parameters will work.

Closure

Closure: the left part of the arrow is the parameter list, the right part of the arrow is the function body.

var variable = (parameters) => function body

Example 5.3

object Anony000 {

def main(args: Array[String]) {

println( "adds(1) value is " +  adds(1) )    // calling

println( "adds(2) value is " +  adds(2) )    // calling

}

var num = 100

val adds = (n:Int) => n + num     // define a closure

}

Output:

adds(1) value is 101

adds(2) value is 102

Explanation:

“val adds = (n:Int) => n + num” defines a closure.

(n:Int) is a parameter

“n + num” is a function body.

String

String is consisted of a series of characters, and it is always enclosed in double quotation marks.

A string is an immutable object, therefore the String object cannot be modified.   The syntax to create a string is as follows:

var string_name = "string_value";

or

var string_name     : String = "string_value";

Example 5.4

object Str000 {

val book = "Go in 8 Hours"     // create a string

def main(args: Array[String]) {

println( book )

}

}

Output:

Go in 8 Hours

Explanation:

“val book = "Go in 8 Hours" ” creates a string.

String Length

The syntax to get the length of a string is as follows:

myString    . length()

Example 5.5

object Leng000 {

def main(args: Array[String]) {

var myString = "Rust in 8 Hours";

var leng = myString.length() ;    // get the length

println( "The string length is : " + leng );

}

}

Output:

The string length is : 15

Explanation:

“myString. length();” gets the length of the string.

String Connection

The syntaxes to connect two strings are as follows:

string1    . concat(string2);

or

string1 + string2 ;

Example 5.6

object Con000 {

def main(args: Array[String]) {

var str1 = "JAVA";

var str2 =  "C#";

var str3 =  "in 8 Hours： ";

println( str1.concat(str3) );    // connecting

println( str2 + str3 );      // connecting

}

}

Output:

JAVA in 8 Hours

C# in 8 Hours

Explanation:

“str1. concat(str3) );” connects str1 with str3.

“str2+str3” connects str2 with str3.

String Functions

Frequently Used String Functions List

char charAt(int index)

Returns the character of the specified position

int compareTo(Object o)

Compare strings with objects

int compareTo(String anotherString)

Compare two strings in dictionary order

int compareToIgnoreCase(String str)

Compare two strings in dictionary order, regardless of case

String1 concat(String2 str)

Connects the specified string2 to the end of the string1

boolean contentEquals(StringBuffer sb)

Compares this string to the specified stringbuffer .

boolean endsWith(String suffix)

Tests whether this string ends with the specified suffix

boolean equals(Object anObject)

Compares this string to the specified object

int hashCode()

Returns the hash code for this string

int indexOf(int ch)

Returns the index of this string

int indexOf(String str)

Returns the index of the specified string at the first occurrence

String intern()

Returns a canonical representation of a string object

int lastIndexOf(int ch)

Returns the index of the specified character at the last occurrence

int lastIndexOf(String str)

Returns the index where the string appears on the right

int length()

Returns the length of this string

boolean matches(String regex)

Tells whether this string matches a given regular expression

String replace(char oldChar, char newChar)

Newchar replaces oldchar

String[] split(String regex)

Split this string according to the regular expression

boolean startsWith(String prefix)

Tests whether this string starts with the specified prefix

boolean startsWith(String prefix, int toffset)

Tests whether this string starts with the specified prefix .

String substring(int beginIndex)

Returns a new substring

String substring(int beginIndex, int endIndex)

Returns a substring

char[] toCharArray()

Convert a string to an array of characters

String toLowerCase()

Convert all characters in string to lowercase

String toString()

Returns a string

String toUpperCase()

Convert all characters in string to uppercase

String trim()

Removes the beginning and end blank of the string

Hour 6

Array

An array is a particular variable, which can contain one or more values at a time.

(1) The first syntax to create an array is as follows:

val array_name = new Array[Type](length)

array-name(index0) = value0;

array-name(index1) = value1;

array-name(index2) = value2;

Example 6.1

val color =  new Array[String](3)       // create an array

color(0) = "Red";        // assign value

color(1) = "Blue";

color(2) = "Green"

Explanation:

Above code creates an array, array name is “color”, and it has three elements: color (0), color (1), color (2). Its indexes are 0, 1, and 2. Its values are red, blue, and green.

Note: The index of the first element is 0, and the index of the last element is “array. length -1”.

(2) The second syntax to create an array as follows:

val array_name = Array (“value0”, “value1”, “value2”);

The  syntax to access an array element is as follows:

array_name(index)

Note: The index of the first array element is 0.

Example 6.2

object Arr000 {

def main(args: Array[String]) {

var color = Array("Red", "Blue", "Green")   // create an array

print( color(0) )    // access the first array element

}

}

Output:

Red

Explanation:

“Array("Red", "Blue", "Green")” creates an array with three elements. “color(0)” accesses the first array element.

Access Array Elements

The syntax to access all elements of the array is as follows:

for ( each_element <    - array_name ) { }

Example 6.3

object Acc000 {

def main(args: Array[String]) {

var myArray = Array(0. 1, 0. 2, 0. 3, 0. 4, 0. 5)

for ( num <- 　myArray ) {    // access all elements

println( num )

}

// Calculate the sum of all elements of an array

var sum = 0. 0;

for ( n <- 0 to (myArray.length - 1)) {  // access elements

sum += myArray(n);

}

println("The sum is " + sum);

}

}

Output:

0. 1

0. 2

0. 3

0. 4

0. 5

The sum is 1. 5

Explanation:

“for ( num <- 　myArray ) {    }” accesses all elements.

“myArray. length-1” accesses the last element of the array.

Connect Array

The syntax to connect two arrays is as follows:

concat( array1, array2)

Befor using concat(), you need to import Array. _ tool.

Example 6.4

import Array._           // import array tools for concat()

object Merge000 {

def main(args: Array[String]) {

var array1 = Array(0. 1, 0. 2, 0. 3)

var array2 = Array(0. 4, 0. 5, 0. 6)

var array3 = concat( array1, array2)   // connect two arrays

for ( elements <- array3 ) {

println( elements )

}

}

}

Output:

0. 1

0. 2

0. 3

0. 4

0. 5

0. 6

Explanation:

Before using concat(), you need to import Array. _ tool.

“concat( array1, array2)” connects two arrays

Reverse Array Elements

The syntax to reverse all elements of an array is as follows:

array    . reverse. toBuffer

Before using array function, you need to import Array. _ package

Example 6.5

import Array. _

object Rev000 {

def main(args: Array[String]) {

var myArray = Array(0, 1, 2, 3, 4)

for (a: Int <- myArray.reverse.toBuffer ){     // reverse elements

print(a + "  ")

}

}

}

Output:

4  3  2  1  0

Explanation:

“myArray. reverse. toBuffer){  }” reverses elements of the array.

Array Operations

ArrayBuffer is a mutable object, which can be changed during program running.

The syntax to create an ArrayBuffter is as follows:

val arr = ArrayBuffer[Int]()

Before using ArrayBuffer, you need to import scala. collection. mutable. ArrayBuffer

The functions handling list:

arr += element   // append an element at the end of the array

arr ++= Array()   // appends another array at the end of the array

arr . trimEnd(n )     // remove last elements  of the array

arr . insert(index, elements)   // insert elements at the specified index

ar    r . remove(index, elements)   // remove elements at the specified index

Example 6.6

import scala. collection. mutable. ArrayBuffer

import Array. _

object Arr008 {

def main(args: Array[String]) {

val arr = ArrayBuffer[Int]()  // create an empty array

arr += 10  // append an element at the end

// now the element is 10

arr += (11,12,13)  // append multi elements

// now the elements are 10 11 12 13

arr ++= Array(14,15,16)   // append another array

// now the elements are 10 11 12 13 14 15 16

arr. trimEnd(2)   // remove last two elements

// now the elements are 10 11 12 13 14

arr. insert(2,100, 200)  // insert elements at index 2

// now the elements are 10 11 100 200 12 13 14

arr. remove(4,2)   // remove elements at index 4

// now the elements are 10 11 100 200 14

for (myArray: Int <- arr){  // output all elements

print(myArray + "  ")

}

}

}

Output:

10  11  100  200  14

Explanation:

See the function handling list on the above.

Array Sort

The syntax to sort an array is as follows:

array    . sorted. toBuffer

Example 6.7

object Sort003{

def main(args: Array[String]) {

val arr = Array(5, 3, 1, 4, 2, 0)

val sortArr = arr.sorted.toBuffer      // sort the array

for (myArray: Int <- sortArr){   // output all elements

print(myArray + "  ")

}

}

}

Output:

0  1  2  3  4  5

Explanation:

“arr. sorted. toBuffer” sorts the array.

Before sorted,  the sequence of the elements is: 5,3,1,4,2,0

After sorted, the sequence of the elements is: 0,1,2,3,4,5

Hour 7

Scala List

List is an immutable object, which cannot be changed during program running. List can store duplicated objects.

The syntax to define a list is as follows:

val list_name    : List[Type] = List(val1, val2, val3, …)

The operation of List is as follows:

list_name. head   // returns the first element of the list

list_name. last   // returns the last element of the list

list_name. tail   // returns a list except the first element

list_name    . isEmpty   // returns true when the list is empty

Example 7.1

object Color000 {

def main(args: Array[String]) {

val colors = List("Red", "Yellow", "Green")

val color0 = List()

println( "The first color is: " + colors.head )

println( "The last color is: " + colors.last )

println( "The tail color is: " + colors.tail )

println( "The color0 list is empty ? " + color0.isEmpty )

}

}

Output:

The first color is Red.

The last color is Green

The tail color is List(“Yellow”, “Green”)

The color0 is empty? true

Explanation:

list_name. head   // returns the first element of the list

list_name. last   // returns the last element of the list

list_name. tail   // returns a list except the first element

list_name. isEmpty   // returns true when the list is empty

Connect Two Lists

The syntax to connect two lists are as follows:

List1     ::: List2

or

List    . concat (List1, List2)

A new List will return after two lists are connected.

Example 7.2

object conlist000 {

def main(args: Array[String]) {

val title1 = List("Java", "in")

val title2 = List("Ruby", "in")

val title3 = List("8", "Hours")

println(title1 ::: title3 )     // connect two lists

println(List.concat(title2, title3) )   // connect two lists

}

}

Output :

List(“Java”, “in”, “8”, Hours)

List(“Ruby”, “in”, “8”, Hours)

Explanation:

“title1 ::: title3” connects two lists, returns a new list.

“List. concat(title2, title3)” connects two lists, returns a new list.

Scala Set

A Scala Set is a collection of non-repeating objects, all elements of which are unique.

The syntax to create a Set is as follows:

val set_name = Set(val1, val2, val3,…)

The operation of List is as follows:

set_name. head   // returns the first element of the set

set_name. last   // returns the last element of the set

set_name. tail   // returns a set except the first element

set_name    . isEmpty   // returns true when the set is empty

Example 7.3

object Set000 {

def main(args: Array[String]) {

val pets = Set("Tiger", "Lion", "Bear")

val pet0 = Set()       // define an empty Set

println( "The first pet is: " + pets. head )

println( "The last pet is: " + pets. last )

println( "The tail pet is: " + pets. tail )

println( "The pet0 Set is empty ? " + pet0. isEmpty )

}

}

Output:

The first pet is Tiger.

The last pet is Bear

The tail pet is List(“Lion”, “Bear”)

The pet0 is empty? true

Explanation:

set_name. head   // returns the first element of the set

set_name. last   // returns the last element of the set

set_name. tail   // returns a set except the first element

set_name. isEmpty   // returns true when the set is empty

Set Operations

Some operating functions of Set are as follows:

set1 ++ set2     // connect two Sets, returns a disorder Set

set. max     // get the maximum value in the Set

set    . min      // get the minimum value in the Set

Example 7.4

object Test {

def main(args: Array[String]) {

val set1 = Set(0,1,2,3,4,5)

val set2 = Set(6,7,8,9)

var set3 = set1 ++ set2

println("The connected Set is : " )

println(set3)

println( "The minimum element is : " + set3. min )

println( "The maximum element is : " + set3. max )

}

}

Output:

The connected Set is :

Set(0, 5, 1, 6, 9, 2, 7, 3, 8, 4)

The minimum element is : 0

The maximum element is : 9

Explanation:

set1 ++ set2     // connect two Sets, returns a disorder Set

set. max     // get the maximum value in the Set

set. min      // get the minimum value in the Set

Scala Map

Map is a collection of key/value structures, all its values can be obtained by its key, the key in the Map is unique.

The syntax to create a Map is as follows:

val Map_name = Map("key1" -    > "val1", "key2" -> "val2", … )

If use Map, you need to import scala. collection. mutable. Map

The operating methods of Map are as follows:

map_name. keys  // return a Map with all keys

map_name. values  // return a HashMap with all values

map_name    . isEmpty         // return true if the Map is empty

Example 7.5

import scala. collection. mutable. Map

object Map001 {

def main(args: Array[String]) {

val house = Map("door" -> "big",

"window" -> "small",

"wall" -> "high")

val house0 = Map()     // define an empty Map

println( "All keys in the map are : ")

println( house.keys )

println( "All values in the map are : " )

println( house.values )

println( "The hourse is empty ? " + house.isEmpty )

println( "The hourse0 is empty ? " + house0.isEmpty )

}

}

Output:

All keys in the map are :

Set( window, door, wall )

All values in the map are :

HaspMap( small, big, high )

The house is empty ? false

The house0 is empty ? true

Explanation:

map_name. keys  // return a Set with all keys

map_name. values  // return a HashMap with all values

map_name. isEmpty         // return true if the Map is empty

Connect Two Maps

The syntax to connect two Maps is as follows:

map1 ++ map2

Example 7.6

object Map004 {

def main(args: Array[String]) {

val colors1 = Map("green" -> "#006600", "purple" -> "#ff00ff")

val colors2 = Map("grey" -> "#666666", "black" -> "#000000")

var colors = colors1 ++ colors2    // connect two maps

println( "The connected map is : "  )

println( colors )

}

}

Output:

The connected map is:

Map( green -> 　#006600,  purple -> 　#ff00ff,  grey -> 　#666666,  black -> 　#000000 )

Explanation:

“colors1 ++ colors2”    // connect two maps

Map Key & Value

Using “foreach()” can get the Map keys and Values.

map_name    . keys. foreach ( k => map(k) )

For every loop iteration, each key of the map element is assigned to “k”, each value is assigned to “map(k)”, until iterates the last map element.

Example 7.7

object Map002 {

def main(args: Array[String]) {

val books = Map("title" -> "Rust in 8 Hours",

"author" -> "Ray Yao",

"website" -> "www. amazon. com")

books.keys.foreach { k =>        // iteration

print( "Key is: " + k )

println(".    Value is: " + books(k) )}

}

}

Output:

Key is title.   Value is Rust in 8 Hours

Key is author.   Value is Ray Yao

Key is website.   Value is www. amazon. com

Explanation:

“books. keys. foreach{ k => books(k)}” outputs each book’s title and each book’s value.

Hour 8

Tuple

Tuple is a kind of collection that can contain different types of elements.

The syntax to create a Tuple is as follows:

val tuple_name = ( Int_val,  Float_val,  String_val,… )

The syntax to access the elements of Tuple is as follows:

tuple_name. _1    // access the first element

tuple_name. _2    // access the second element

tuple_name    . _3    // access the third element

Example 8.1

object Test {

def main(args: Array[String]) {

val t = (100, 200.88, "Go in 8 Hours")     // create a tuple

println( t._1 )      // access the first element

println( t._2 )      // access the second element

println( t._3 )      // access the third element

}

}

Output:

100

200

Go in 8 Hours

Explanation:

“val t = (100, 200. 88, "Go in 8 Hours") “ creates a tuple

“println( t. _1 )” accesses the first element

“println( t. _2 )” accesses the second element

“println( t. _3 )” accesses the third element

Tuple Iteration

The syntax to iterate the Tuple elements is as follows:

tuple_name    . productIterator. foreach{ k => v }

“k” is the keys of the tuple.

“v” is the values of the tuple.

Example 8.2

object Tup001 {

def main(args: Array[String]) {

val t = (10, 20, 30, 40, 50)

t.productIterator.foreach {       // iterate the tuple

k => println("The value is : " + k )

}

}

}

Output:

The value is : 10

The value is : 20

The value is : 30

The value is : 40

The value is : 50

Explanation:

“t. productIterator. foreach{ k=>v} iterates all elements of the tuple.

Scala Iterator

Iterator is used to access all elements in a collection.

The syntax to use Iterator is as follows:

val obj = Iterator("val1", "val2", "val3", "val4")

“obj” is an object of Iterator.

The operating methods of Iterator are as follows:

obj. next()    // access the next element of the iterator

obj    . hasNext     // check if the next element exists

Example 8.3

object Test {

def main(args: Array[String]) {

val obj = Iterator("C#", "in", "8", "Hours")    // use iterator

while (obj.hasNext ){    // check if the next element exists

Print (obj. next () + " ")    // access the next element

}

}

}

Output:

C# in 8 Hours

Explanation:

“val obj = Iterator("C#", "in", "8", "Hours") “ uses an iterator.

“obj. hasNext)” checks if the next element exists

“obj. next()” accesses the next element in the iterator.

Useful Function in Iterator

There four useful functions in Iterator:

obj. max    // get the maximum value in the iterator

obj. min      // get the minimum value in the iterator

obj. size      // get the number of elements in the iterator

obj    . length   // get the number of elements in the iterator

“obj” is an iterator object

Example 8.4

object It003 {

def main(args: Array[String]) {

val obj1 = Iterator(10,20,30,40,50)

println("The minimum value is :" + obj1.min )

val obj2 = Iterator(60,70,80,90)

println("The maximum value is :" + obj2.max )

val obj3 = Iterator("C#", "in", "8", "Hours")

println("The number of elements is : " + obj3.size )

val obj4 = Iterator("C#", "Interview", "Exam")

println("The number of elements is : " + obj4.length )

}

}

Output:

The minimum value is : 10

The maximum value is : 90

The number of elements is : 4

The number of elements is : 3

Explanation:

obj. max    // get the maximum value in the iterator

obj. min      // get the minimum value in the iterator

obj. size      // get the number of elements in the iterator

obj. length   // get the number of elements in the iterator

Class

Class is an abstract concept, a class represents the commonness and characteristics of something or someone.

Objects are concrete things or people, an object is an instance of one thing or person.

Class is an abstraction of an object, Object is a concrete instance of a class. For example: If the vehicle is a class, then your car is an object.

(1) The syntax to define a class is as follows:

class Class_Name ( parameters ){

……

}

The first letter of class name should be capitalized.

Example 8.5

class Color ( num: Int ){

……

}

Explanation:

“Color” is a class name

“num: Int” is a parameter.

Object

An object is an instance of a class.

val obj = new Class_Name(  );   // create an object

obj. variable_name

obj    . function_name( )

“obj = new Class_Name( );” creates a new object named “obj” for the class.

“obj. variable;” means that “obj” references a variable.

“obj. function_name ( );” means that “obj” references a method.

Example 8.6

val obj = new Color(  ) ;   // create an object “obj”

obj. c1= “yellow";   // an object references a variable c1

obj. c2=”purple”;     // an object references a variable c2

obj. brightness ( );   // an object calls a method brightness()

Explanation:

“val obj = new Color;” creates an object named ”obj”, then references variable “c1” and “c2”.

“obj. brightness ( );” calls the function “brightness ( );”

Class & Object

Example 8.7

import java. io. _    // import the java package for class & object

class MyClass(val a: Int, val b: Int) {   // define a class

var x: Int = 0     // the member of the class

var y: Int = 0     // the member of the class

def func(){     // the member of the class

x = a * 2

y = b * 3

}

}

object Study {

def main(args: Array[String]) {

val obj = new MyClass(100, 200)    // create an object

obj.func()      // the object calls the method

println ( obj.x );     // the object references the variable x

println ( obj.y );     // the object references the variable y

}

}

Output:

200

600

Explanation:

“class MyClass(val a: Int, val b: Int) {  }” defines a class.

“val obj = new MyClass(100, 200)” creates an object.

“obj. func()”: the object calls the method func()

“obj. x” : the object references the variable x

“obj. y” : the object references the variable y

Appendix 1

Extends

A class can be extended by a subclass. The subclass will inherit all members of the super class.

If the parameter or method in the subclass overrides the parameters or method in the super class, you should use the keyword “override”.

The syntax to extend a super class is as follows:

class SubClass (override arg    : type) extends SuperClass(arg)

Example A1

import java. io. _    // import the java package for class & object

class MyClass (val a: Int, val b: Int) {   // super class

var x: Int = 0     // the member of the class

var y: Int = 0     // the member of the class

def func(){     // the member of the class

x = a * 2

y = b * 3

}

}

class SubClass(override val a: Int, override val b: Int) extends MyClass (a, b){      // subclass extends the super class

var z: Int = a + b      // the member of the subclass

}

object Study {

def main(args: Array[String]) {

val obj = new SubClass (100, 200)  // create a sub object

obj. func()     // func() becomes a member of the subclass

println ( obj. x);   // x becomes a member of the subclass

println ( obj. y);   // y becomes a member of the subclass

println ( obj. z);

}

}

Output:

200

600

300

Explanation:

class SubClass(override val a: Int, override val b: Int) extends MyClass (a, b){   }   // subclass extends the super class

While a subclass extends a super class, the subclass will inherit all members of the super class.

Access Modifiers

The access modifiers of Scala are: private, protected, and the public. “public” is a default access modifier.

Private

The private members in the nested class cannot be accessed by the outer class.

The private members in the current class cannot be accessed by the other class.

The private member in the current class can be only accessed by the current class.

Example A2

object Acc000{

class Study{

private def func(){ println("……") }   // private function

......

func()   // Correct ! Call a private function in the same class

}

class Another{

obj.func()   // Error! Call a private function in another class

}

}

Explanation:

“private def func(){ println("…") }“ defines a private function

“func()”: Correct! Call a private function in the same class.

“obj. func()”:  Error! Call a private function in another class.

Example A3

import java. io. _

class MyClass(val a: Int, val b: Int) {

var x: Int = 0

var y: Int = 0

private def func(){     // define a private method

x = a * 2

y = b * 3

}

func()   // Correct ! Call the private method in the same class

}

object Study {

def main(args: Array[String]) {

val obj = new MyClass(100, 200)

println ( obj. x );

println ( obj. y );

}

}

Output:

200

600

Explanation:

“private def func(){   }” defines a private method.

“func()”  calls the private method in the same class successfully! Correct!

Protected

A Protected member can be accessed by a subclass of the class, and cannot be accessed by another class.

Example A4

class Super{

protected def m() {     // define a protected member

println("...... ")

}

}

class Sub extends Super{      // inherit

m()     // Correct ! Subclass can access the protected member

}

class Another{

obj.m() // Error!  Another class can ’ t access protected member

}

Explanation:

“protected def m() { }”defines a protected member.

“m()”:Correct! Subclass can access the protected member

“obj. m()”:Error! Another class can’t access protected member

Example A5

import java. io. _

class MyClass(val a: Int, val b: Int) {

var x: Int = 0

var y: Int = 0

protected def func(){     // define a protected member

x = a * 2

y = b * 3

}

}

class SubClass(override val a: Int, override val b: Int) extends MyClass (a, b){     // inherit

var z: Int = a + b

func()   // OK ! SubClass can accesses the protected member .

}

object Study {

def main(args: Array[String]) {

val obj = new SubClass(100, 200)

println ( obj. x );

println ( obj. y );

println ( obj. z );

}

}

Output:

200

600

300

Explanation:

“protected def func(){  }” defines a protected member.

“func()”:  SubClass can accesses the protected member successfully. Correct!

Exception

If an exception happens in Scala program,  Scala terminates the code by throwing an exception

The Scala program usually has following exceptions:

Column 1

Column 2

ArithmeticException

ArrayStoreException

AwtException

ClassCastException

ClassNotFoundException

IllegalArgumentException

IndexOutOfBoundsException

InstantiationException

InterruptedException

NoSuchMethodException

NumberFormatException

RuntimeException

EOFException

FileNotFoundException

InterruptedIOException

IOException

UTFDataException

To resolve the exceptions in column 1, please import Java. lang. *

To resolve the exceptions in column 2, please import Java. io. *

The syntax to handle the exception is as follows:

try {     // try some code where exception may happen

} catch {    // catch one of the exceptions

case e: Exception 1 => {

}

case e: Exception 2 => {

}

case e: Exception 3 => {

}

} finally {      // must execute

}

Example A6

import java. io. FileReader

import java. io. FileNotFoundException

import java. lang. RuntimeException

import java. lang. NumberFormatException

object Except000 {

def main(args: Array[String]) {

try {  // try some code where the exception may happen

val myFile = new FileReader("myFile. txt")

} catch {    // catch one of the exceptions

case e: FileNotFoundException => {

println("The file cannot be found. ")

}

case e: RuntimeException => {

println("Runtime Exception")

}

case e: NumberFormatException => {

println("Number Format Exception")

}

} Finally {     // must execute

println("Check the file carefully! ")

}

}

}

Output:

The file cannot be found.

Check the file carefully!

Explanation:

Assume myfile. txt does not exist, so exception happens.

“try {  }” tries some code where exception may happen

“catch {  }” catches one of the exceptions.

“Finally {  }”  must execute these codes.

Appendix 2

Tests

Please choose the correct answer.

01.

fill in HelloWorld {      // This is a Hello World program

def main(args: Array[String]) {

println("Hello, world! ")

}

}

A. program     B. class     C. public     D. object

02.

object Var001 {

def main(args: Array[String]){

var myVar1: fill in = 1000    // declare a data type

print(myVar1)

}

}

A. string     B. float     C. Int     D. int

03

object Ifelse001 {

def main(args: Array[String]) {

var a=100; var b=200;

if (a>b) {print ("a is greater than b. ")}

fill in { print ( "a is less than b" );}     // do this

}

}

A. then     B. else     C. than     D. otherwise

04.

object Test {

def main(args: Array[String]) {

println( "The result is : " + mul(50,2) );   // call the method

}

fill in mul( x:Int, y:Int ) : Int = {   // define a method

var result:Int = 0

result = x * y

return result        // return value

}

}

A. function     B. void     C. method     D. def

05.

object Arr000 {

def main(args: Array[String]) {

var color = fill in ("Red", "Blue", "Green")    // create an array

print( color(0) )    // access the first array element

}

}

A. Array     B. new Array     C. array     D. new array

06.

list_name. head   // returns the first element of the list

list_name. tail   // returns fill in ?

list_name. isEmpty   // returns true when the list is empty

1. the last element of the list

2. an empty list

3. a list except the first element

4. an zero element in the end.

07.

// create a tuple

val t = fill in 100, 200. 88, "Go in 8 Hours" fill in

A. [     ]       B. (     )        C. {     }        D. <     >

08.

The syntax to extend a super class is as follows:

class SubClass (override arg    : type) fill in SuperClass(arg)

A. inherit        B. inherits        C. extend        D. extends

09.

About Multi-line String Type

Multi-line String Type are defined by fill in quotes.

A. single        B. double        C. treble        D. quadruple

10.

object Val002 {

def main(args: Array[String]){

fill in Con1 = "C# in "     // define a constant

fill in Con2 : Int = 8        // define a constant

fill in Con3 : String = " Hours"     // define a constant

print(Con1 + Con2 + Con3);

}

}

A. val        B. var        C. const        D. constant

11.

object For001 {

def main(args: Array[String]) {

var y = 0;

for( y <- 0 fill in 8){   // run 7 times

print( y );

}

}

}

A. to        B. till      C. <      D. until

12.

About Closure: the left part of the arrow is _______, the right part of the arrow is the function body.

var variable = (     fill in ) => function body

A. a closure name

B. a parameter list

C. a return type

D. a loop statement

13.

The syntax to create an array is as follows:

val array_name = fill in [Type](length)

array-name(index0) = value0;

array-name(index1) = value1;

array-name(index2) = value2;

A. Array     B. new Array     C. array     D. new array

14.

object conlist000 {

def main(args: Array[String]) {

val title1 = List("Java", "in")

val title2 = List("Ruby", "in")

val title3 = List("8", "Hours")

println(title1 fill in title3)     // connect two lists

println(List. concat(title2, title3))   // connect two lists

}

}

A. :         B. ::         C. :::         D. ::::

15.

The syntax to define a class is as follows:

fill in ( parameters ){

……

}

A. Class_Name Class

B. Class_Name class

C. Class Class_name

D. class Class_Name

16.

Which following statement is not correct?

A. The private members in the nested class cannot be accessed by the outer class.

B. The private members in the current class cannot be accessed by the other class.

C. The private member in the current class can be only accessed by the current class.

D.   The private members in the nested class can be accessed by the outer class.

17.

Which following statement is not correct?

A. The first letter of all class names should be capitalized.

B. All method names start with a lowercase letter.

C. Scala is a case-insensitive language.

D. A semicolon is used to end a line of statement.

18.

What is the output according to the following code?

object log000 {

def main(args: Array[String]) {

var x=true; var y=false;

var a = x && y;   print ( a + “ “ );

var b = x || y;   print ( b + “ “  );

var c = ! x;   print ( c + “ “  );

}

}

A. true  false  false

B. false  true  false

C. true  true  false

D. false  false true

19.

object For000 {

def main(args: Array[String]) {

var x = 0;

for( x <- 0  fill in 8){    // run 8 times

print( x );

}

}

}

A. to        B. till      C. <      D. until

20.

object Con000 {

def main(args: Array[String]) {

var str1 = "JAVA";

var str2 =  "C#";

var str3 =  "in 8 Hours： ";

println( str1. fill in (str3) );    // connect two strings

println( str2 + str3 );

}

}

A. connect        B. join        C. concat        D. link

21.

import Array. _

object Rev000 {

def main(args: Array[String]) {

var myArray = Array(0, 1, 2, 3, 4)

for (a: Int <- myArray. fill in ){     // reverse elements

print(a + "  ")

}

}

}

A. reverse

B. reverse()

C. reverse. ArrayBuffer

D. reverse. toBuffer

22.

object Map004 {

def main(args: Array[String]) {

val colors1 = Map("green" -> "#006600", "purple" -> "#ff00ff")

val colors2 = Map("grey" -> "#666666", "black" -> "#000000")

var colors = colors1 fill in colors2   // connect two maps

println( "The connected map is : "  )

println( colors )

}

}

A. +        B. ++        C. +++        D. ++++

23.

val obj = fill in Class_Name(  );   // create an object

obj. variable_name( )

obj. function_name( )

A. create        B. object        C. new        D. class

24.

try {

} catch {

case e: Exception 1 => {

}

case e: Exception 2 => {

}

case e: Exception 3 => {

}

} fill in {      // must execute

}

A. last        B. lastly        C. final        D. finally

Answers

01 . D

13 . B

02 . C

14 . C

03 . B

15 . D

04 . D

16 . D

05 . A

17 . C

06 . C

18 . B

07 . B

19 . A

08 . D

20 . C

09 . C

21 . D

10 . A

22 . B

11 . D

23 . C

12 . B

24 . D

Note:

This book is only for beginners, it is not suitable for experienced programmers .

Source Code Download Link:

https://forms . aweber . com/form/76/1081568876 . htm

Source Code Download

Ray Yao’s eBooks & Books on Amazon

Advanced C++ Programming by Ray Yao

Advanced Java Programming by Ray Yao

AngularJs Programming by Ray Yao

C# Programming by Ray Yao

C# Interview & Certification Exam

C++ Programming by Ray Yao

C++ Interview & Certification Exam

Django Programming by Ray Yao

Go Programming by Ray Yao

Html Css Programming by Ray Yao

Html Css Interview & Certification Exam

Java Programming by Ray Yao

Java Interview & Certification Exam

JavaScript Programming by Ray Yao

JavaScript 50 Useful Programs

JavaScript Interview & Certification Exam

JQuery Programming by Ray Yao

JQuery Interview & Certification Exam

Kotlin Programming by Ray Yao

Linux Command Line

Linux Interview & Certification Exam

MySql Programming by Ray Yao

Node.Js Programming by Ray Yao

Php Interview & Certification Exam

Php MySql Programming by Ray Yao

PowerShell Programming by Ray Yao

Python Programming by Ray Yao

Python Interview & Certification Exam

R Programming by Ray Yao

Ruby Programming by Ray Yao

Rust Programming by Ray Yao

Scala Programming by Ray Yao

Shell Scripting Programming by Ray Yao

Visual Basic Programming by Ray Yao

Visual Basic Interview & Certification Exam

Xml Json Programming by Ray Yao

Source Code Download Link:

https://forms . aweber . com/form/76/1081568876 . htm

Table of Contents

Hour 1

What is Scala Language?

The Feature of Scala

Install JDK

Install Scala

Hour 2

“Hello World” Program

Basic Grammar

Scala Keywords

Scala Comment

Package

Data Type

Hour 3

Variables

Declare Variable Type

Declare Multi Variables

Constants

Arithmetical Operators

Comparison Operators

Logical Operators

Assignment Operators

Hour 4

If Statement

If-else Statement

If…else if…else

While Loop

Do-While Loop

For Loop (1)

For Loop (2)

For Loop (3)

Hour 5

Method

Default Parameters

Closure

String

String Length

String Connection

String Functions

Hour 6

Array

Access Array Elements

Connect Array

Reverse Array Elements

Array Operations

Array Sort

Hour 7

Scala List

Connect Two Lists

Scala Set

Set Operations

Scala Map

Connect Two Maps

Map Key & Value

Hour 8

Tuple

Tuple Iteration

Scala Iterator

Useful Function in Iterator

Class

Object

Class & Object

Appendix 1

Extends

Private

Protected

Exception

Appendix 2

Tests

Answers

Source Code Download