Why types exist
Every value in Scala has a data type, and the compiler knows it before the program runs. The type decides what operations make sense. Take this line:
println(a + b)
If a and b are numbers, + adds them. If they are strings, + joins them:
val a = 10
val b = -5
println(a + b) // 5
val c = "Hello "
val d = "world!"
println(c + d) // Hello world!
The same symbol does different jobs because Scala looks at the types. The types also catch nonsense early. Multiplying two strings has no meaning, and the compiler refuses:
val x = "peanut"
val y = "butter"
println(x * y)
-- [E007] Type Mismatch Error ---------------------------------------------
| println(x * y)
| ^
| Found: (y : String)
| Required: Int
A String can be multiplied by an Int, which repeats it, so "ab" * 3 is "ababab". A string on the right is what the compiler can't accept. The program doesn't run at all; this is a compile-time error, not a crash in the middle of execution.
The basic types
| Type | Holds | Examples |
|---|---|---|
Int | whole numbers | 3, -12 |
Double | numbers with a decimal point | 3.14, -0.5 |
String | text | "John Doe" |
Boolean | true or false | true, false |
Char | one character | 'a', '?' |
Some details that matter:
StringversusChar. Strings use double quotes and chars use single quotes."a"is a string with one character, and'a'is aChar. They are different types.Inthas limits. It uses 32 bits, so it covers about plus or minus 2.1 billion. Going past the top wraps around silently:Int.MaxValue + 1is-2147483648. For bigger whole numbers useLong.- Whole numbers and decimals are separate.
7 / 2is3because both sides areInt, while7 / 2.0is3.5. - Booleans are lowercase.
trueandfalseare written in lowercase.
Declaring a type
You can state a variable's type after its name, separated by a colon: val myInt: Int = 5. Scala can often work the type out from the value, so val myInt = 5 would also be an Int. Writing the type makes the intention visible, and the compiler checks the value against it.
The exercise step by step
- An integer. Create
myIntwith typeIntand give it a whole number such as 5. - A decimal. On the next line create
myFloatwith typeDouble. The name says float, but in Scala the usual decimal type isDouble, so the value is something like3.14. KeepmyIntabove it. - Text. Create
myStringwith typeStringand a value in double quotes. - A yes or no. Create
myBoolwith typeBooleanand set it totrueorfalse. Keep the three earlier lines.
The solution in Scala
val myInt: Int = 5
val myFloat: Double = 3.14
val myString: String = "Hello"
val myBool: Boolean = true
Each line follows the same pattern: val, the name, a colon, the type, an equals sign and a value. val means the name can't be assigned a different value later. Scala also has a type called Float, with less precision than Double, and a decimal literal such as 3.14 is a Double unless it ends in f, as in 3.14f. The variable name myFloat is only a name; its declared type is what counts.
Common mistakes
- A value that doesn't match the type.
val myInt: Int = 3.14is a compile error, because Scala does not cut a decimal down to a whole number for you. The error showsFound: DoubleandRequired: Int. - Forgetting quotes.
val myString: String = Hellomakes Scala look for a name calledHello. - Single quotes for text.
'Hello'is not a validChar, because aCharholds exactly one character. - Capitalised booleans.
Trueis not a Scala keyword. Writetrue. - Removing earlier lines. Later steps keep the earlier variables, so add new lines instead of replacing old ones.
Key takeaways
- Every value has a type, and Scala checks types while compiling.
- The basic types are
Int,Double,String,BooleanandChar. - The type follows the name after a colon, and the value must match it.
- The same operator can mean different things for different types, and some combinations are rejected.
