Sage-Code Laboratory
index<--

Scala Types

Scala is a strongly typed language, similar to Java and C++. Unlike for Java there are no native types in Scala. All data types are part of Scala Unified Type hierarchy. The root of all types is called "Any" and is a Class. Therefore in Scala everyting is an Object.
ScalaTypes

Type Hierarchy

Notes:

Nothing and Null

The "Nothing" is a subtype of all types. There is no value that has type Nothing. A common use is to signal special cases such as a thrown exception, program exit, or an infinite loops.

The "Null" is a subtype of all reference types. It has a single value identified by the keyword literal "null". Null is provided mostly for interoperability with other JVM languages and should almost never be used in Scala code.

Type Casting

Values can be safely casted in a single direction. This is happening automatically and does not require a special syntax. The compiler will not complain if the conversion is safe.

TypeConversion

Safe Conversion

Examples:

//demo for type conversion
val heart: Char = '♥'    // Character
val number: Int = heart  // 2665

// demo for numeric conversion
val x: Long   = 125 // long integer 
val y: Double = x   // 1.25E2

Type Properties

Scala is following Java types. Though scala types are boked values, ultimately these types contain the data that is handled by JVM. And JVM is handling native types. So the underline value of these types have same limits and capacity as the native Java types.

DATATYPE DEFAULT VALUE DESCRIPTION
Boolean false true or false (theoretical one byte)
Byte 0 8 bit signed value. Range:-128 to 127
Short 0 16 bit signed value. Range:-215 to 215-1
Char ‘\u000’ 16 bit unsigned unicode character. Range:0 to 216-1
Int 0 32 bit signed value. Range:-231 to 231-1
Long 0L 64 bit signed value. Range:-263 to 263-1
Float 0.0F 32 bit IEEE 754 single-Precision float
Double 0.0D 64 bit IEEE 754 double-Precision float

Scala Strings

Scala has a very useful type you can use to define strings. This type has features that makes it more like Ruby strings than Java. When you define a string you use double quotes "...". The String type is used automatically when you declare a string with initial value:

Examples:

//string declaration demo
val firstName = "Elucian"
val lastName  = "Moise"
val fullName  = firstName + " " + LastName

Note: 

The strings can be concatenated using "+" operator. This operator is polymorphic. It can add numbers to strings, result is of course a concatenation.

Multiline strings

Scala has support for multiline strings. As you maybe know this is available in Python but not in Java. To make a multiline string you must use triple quotes: """...""". There is a problem about the indentation that is resolved elegandly using separator "|" after indentation spaces and call method: stripMargin.

Example:

In this example we show a paragraph written in a foreign language called Maj. As you can see the test span several lines and every line starts with vertical "|". Method stripMargin will eliminate this symbol but will preserve new lines.

//long string declaration demo
val majText = """kaplo la ome sebo lege de vola, no sonu ni moda una Apena 
                |zolu ablo sh volu; sua aripe sonu tro piko sh yc lifu sua 
                |unto piko-boda abo el sola; el Apena, zogu volu ora-vi ipo 
                |Apene no kocu ke Xume siku kh no sonu poso.""".stripMargin

String Comparison

You can compare two strings using regular comparison operators: "==", "<", ">". This feature is very important. Many developers fall into a trap when they do this comparison in Java. Becouse in Java symbol "==" can not be used to compare two strings.

Example:

//define 3 strings for testing
val str1 = "this is a test"
val str2 = "this " + "is " + "a " + "test"
val str2 = "this"

// check comparison operators
str1 == str2 // true
str1 > str3  // true

// you can do this same using a method
str1.eqials(str2) //true

String Interpolation

We can use symbol "$" in front of identifiers like ($identifier) or expressions like ${expression} to create a string template that will be resolved at runtime. The expressions will be evalueated and replaced. This is more convenient than string format functions found in Java and Python.

Example:

Notice, for string interpolation to work, string is starting with prefix: (s").

//interpolation demo
val firstName = "John"
val lastName  = "Doe"
println(s"Name: $firstName $lastName")
println(s"I know math: 2 + 2 = ${2 + 2}")

Output (Scala REPL):

scala> val firstName = "John"
firstName: String = John

scala> val lastName  = "Doe"
lastName: String = Doe

scala> println(s"Name: $firstName $lastName")
Name: John Doe

scala> println(s"I know math: 2 + 2 = ${2 + 2}")
I know math: 2 + 2 = 4

Touples

A tuple is a class that enable you to hold different items groupped in the same container. A touple literal is very simple a list of constant literals separated by comma and enclosed in round brackets: (...).

//define 2 touples
val t2 = (1, 2) 
val t6 = (1, "one", 2, "two", 3, "three")

//using tuple fields
println(t6._1) // 1
println(t6._2) // one

//unpacking tuple into individual values
val (x, y, z) = (1, 2 ,3)

//ignore elements in the middle
val ( s1,_,_,_,_,s6) = t6

Alternative notation: You can use arrow operator: "->" to create a pair of elements as a tuple. This notation is mostly used to define maps. We will check it later when we study collections.

//define 3 touples
val pair1 = 1 -> "one"
val pair2 = 2 -> "two"
val pairs = (pair1, pair2) // touple of touples

//check the results
println(pair1.toString())  // (1,one)
println(pair2.toString())  // (2,two)
println(pairs.toString())  // ((1,one),(2,two))

Read next: Functions