This is the first blog in the series Small steps to Scala which are notes and code snippets gathered from projects, books, googling around or learning from the great people I've been working with.
With the assumption that you have the Scala interpreter installed and a Linux machine, we will start with the basics.
- Scala interpreter
- val & var
- common types
- operators & functions
Once you install Scala, run
scala in your shell and you should see something similar to:
Welcome to Scala 2.11.8 (OpenJDK 64-Bit Server VM, Java 1.8.0_111). Type in expressions for evaluation. Or try :help. scala>
This is the Scala REPL (Read, Evaluate, Print, Loop) which will take your input and behind the scenes will compile it into bytecode and execute it.
scala> 12 + 3 / 5 res0: Int = 12 scala> "String " + res0 res1: String = String 12
As one can see in the example above, there is no need to specify the type of the variable. Scala will do its best to infer the type and return the proper
val & var variables
Variables are declared with
var, while constants are declared with
scala> var name="George" name: String = George scala> name = "Scala" name: String = Scala
The contents of the variable can be changed, however the type must be preserved, otherwise
type mismatch error will be thrown.
This cannot be done with constants declared with
val. An attempt to do so will result in a
reassignment to val error.
scala> val t = 5 t: Int = 5 scala> t = 4 <console>:12: error: reassignment to val t = 4 ^
These are some of the most common types used in Scala.
|Byte||8 bit signed value. Range from -128 to 127|
|Short||16 bit signed value. Range -32768 to 32767|
|Int||32 bit signed value. Range -2147483648 to 2147483647|
|Long||64 bit signed value. -9223372036854775808 to 9223372036854775807|
|Float||32 bit IEEE 754 single-precision float|
|Double||64 bit IEEE 754 double-precision float|
|Char||16 bit unsigned Unicode character. Range from U+0000 to U+FFFF|
|String||A sequence of Chars|
|Boolean||Either the literal true or the literal false|
|Unit||Corresponds to no value|
|Null||null or empty reference|
|Nothing||The subtype of every other type; includes no values|
|Any||The supertype of any type; any object is of type Any|
|AnyRef||The supertype of any reference type|
Operators & functions
% are methods.
<< are also methods.
Here is a full list of operators in Scala.
a + bis the same with
1 to 10is the same with
a method bis the same with
scala> 2 + 3 == 2.+(3) res2: Boolean = true scala> var a = 2 a: Int = 2 scala> a+=1 scala> a res4: Int = 3
[+] Useful links
Disclaimer: This is by no means an original work it is merely meant to serve as a compilation of thoughts, code snippets and teachings from different sources.