2013-07-29 16:57:44 +04:00
|
|
|
---
|
2013-07-30 02:59:12 +04:00
|
|
|
language: Scala
|
2013-08-02 20:43:54 +04:00
|
|
|
filename: learnscala.scala
|
2013-07-30 03:03:28 +04:00
|
|
|
contributors:
|
|
|
|
- ["George Petrov", "http://github.com/petrovg"]
|
2013-08-02 20:43:54 +04:00
|
|
|
- ["Dominic Bou-Samra", "http://dbousamra.github.com"]
|
2013-07-29 18:14:37 +04:00
|
|
|
filename: learn.scala
|
2013-07-29 16:57:44 +04:00
|
|
|
---
|
|
|
|
|
2013-07-29 18:14:37 +04:00
|
|
|
Scala - the scalable language
|
|
|
|
|
2013-08-02 20:47:13 +04:00
|
|
|
```cpp
|
2013-07-29 18:14:37 +04:00
|
|
|
|
2013-07-28 23:52:32 +04:00
|
|
|
/*
|
|
|
|
Set yourself up:
|
|
|
|
|
|
|
|
1) Download Scala - http://www.scala-lang.org/downloads
|
|
|
|
2) unzip/untar in your favourite location and put the bin subdir on the path
|
|
|
|
3) Start a scala REPL by typing scala. You should see the prompt:
|
|
|
|
|
|
|
|
scala>
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
This is the so called REPL. You can run commands in the REPL. Let's do just
|
|
|
|
that:
|
2013-07-28 23:52:32 +04:00
|
|
|
*/
|
|
|
|
|
|
|
|
println(10) // prints the integer 10
|
|
|
|
|
|
|
|
println("Boo!") // printlns the string Boo!
|
|
|
|
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// Some basics
|
2013-06-30 11:52:21 +04:00
|
|
|
|
|
|
|
// Printing, and forcing a new line on the next print
|
|
|
|
println("Hello world!")
|
|
|
|
// Printing, without forcing a new line on next print
|
|
|
|
print("Hello world")
|
|
|
|
|
|
|
|
// Declaring values is done using either var or val
|
2013-08-02 20:39:30 +04:00
|
|
|
// val declarations are immutable, whereas var's are mutable. Immutablility is
|
|
|
|
// a good thing.
|
2013-06-30 11:52:21 +04:00
|
|
|
val x = 10 // x is now 10
|
|
|
|
x = 20 // error: reassignment to val
|
|
|
|
var x = 10
|
|
|
|
x = 20 // x is now 20
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// Single line comments start with two forward slashes
|
|
|
|
/*
|
|
|
|
Multi line comments look like this.
|
|
|
|
*/
|
2013-06-30 11:52:21 +04:00
|
|
|
|
|
|
|
// Boolean values
|
|
|
|
true
|
|
|
|
false
|
|
|
|
|
|
|
|
// Boolean operations
|
|
|
|
!true // false
|
|
|
|
!false // true
|
|
|
|
true == false // false
|
|
|
|
10 > 5 // true
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// Math is as per usual
|
|
|
|
1 + 1 // 2
|
|
|
|
2 - 1 // 1
|
|
|
|
5 * 3 // 15
|
|
|
|
6 / 2 // 3
|
2013-06-30 11:52:21 +04:00
|
|
|
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// Evaluating a command in the REPL gives you the type and value of the result
|
2013-07-28 23:52:32 +04:00
|
|
|
|
|
|
|
1 + 7
|
|
|
|
|
|
|
|
/* The above line results in:
|
|
|
|
|
|
|
|
scala> 1 + 7
|
|
|
|
res29: Int = 8
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
This means the result of evaluating 1 + 7 is an object of type Int with a
|
|
|
|
value of 8
|
2013-07-28 23:52:32 +04:00
|
|
|
|
|
|
|
1+7 will give you the same result
|
|
|
|
*/
|
|
|
|
|
|
|
|
|
2013-07-30 02:59:12 +04:00
|
|
|
// Everything is an object, including a function. Type these in the REPL:
|
2013-07-28 23:52:32 +04:00
|
|
|
|
|
|
|
7 // results in res30: Int = 7 (res30 is just a generated var name for the result)
|
|
|
|
|
|
|
|
// The next line gives you a function that takes an Int and returns it squared
|
|
|
|
(x:Int) => x * x
|
|
|
|
|
|
|
|
// You can assign this function to an identifier, like this:
|
|
|
|
val sq = (x:Int) => x * x
|
|
|
|
|
|
|
|
/* The above says this
|
|
|
|
|
|
|
|
sq: Int => Int = <function1>
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
Which means that this time we gave an explicit name to the value - sq is a
|
|
|
|
function that take an Int and returns Int.
|
2013-07-28 23:52:32 +04:00
|
|
|
|
|
|
|
sq can be executed as follows:
|
|
|
|
*/
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
sq(10) // Gives you this: res33: Int = 100.
|
2013-07-28 23:52:32 +04:00
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// Scala allows methods and functions to return, or take as parameters, other
|
|
|
|
// functions or methods.
|
2013-06-30 11:52:21 +04:00
|
|
|
|
|
|
|
val add10: Int => Int = _ + 10 // A function taking an Int and returning an Int
|
|
|
|
List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element
|
|
|
|
|
|
|
|
// Anonymous functions can be used instead of named functions:
|
|
|
|
List(1, 2, 3) map (x => x + 10)
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// And the underscore symbol, can be used if there is just one argument to the
|
|
|
|
// anonymous function. It gets bound as the variable
|
2013-06-30 11:52:21 +04:00
|
|
|
List(1, 2, 3) map (_ + 10)
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// If the anonymous block AND the function you are applying both take one
|
|
|
|
// argument, you can even omit the underscore
|
2013-06-30 11:52:21 +04:00
|
|
|
List("Dom", "Bob", "Natalia") foreach println
|
|
|
|
|
2013-07-29 12:29:14 +04:00
|
|
|
|
|
|
|
|
|
|
|
// Data structures
|
|
|
|
|
|
|
|
val a = Array(1, 2, 3, 5, 8, 13)
|
|
|
|
a(0)
|
|
|
|
a(3)
|
|
|
|
a(21) // Throws an exception
|
|
|
|
|
|
|
|
val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo")
|
|
|
|
m("fork")
|
|
|
|
m("spoon")
|
2013-07-29 16:53:55 +04:00
|
|
|
m("bottle") // Throws an exception
|
|
|
|
|
|
|
|
val safeM = m.withDefaultValue("no lo se")
|
|
|
|
safeM("bottle")
|
|
|
|
|
|
|
|
val s = Set(1, 3, 7)
|
|
|
|
s(0)
|
|
|
|
s(1)
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
/* Look up the documentation of map here -
|
|
|
|
* http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map
|
2013-07-29 19:03:49 +04:00
|
|
|
* and make sure you can read it
|
|
|
|
*/
|
|
|
|
|
2013-07-29 16:53:55 +04:00
|
|
|
|
|
|
|
// Tuples
|
|
|
|
|
2013-07-31 23:52:59 +04:00
|
|
|
(1, 2)
|
|
|
|
|
|
|
|
(4, 3, 2)
|
|
|
|
|
|
|
|
(1, 2, "three")
|
|
|
|
|
|
|
|
(a, 2, "three")
|
|
|
|
|
|
|
|
// Why have this?
|
|
|
|
val divideInts = (x:Int, y:Int) => (x / y, x % y)
|
|
|
|
|
|
|
|
divideInts(10,3) // The function divideInts gives you the result and the remainder
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// To access the elements of a tuple, use _._n where n is the 1-based index of
|
|
|
|
// the element
|
2013-07-31 23:52:59 +04:00
|
|
|
val d = divideInts(10,3)
|
|
|
|
|
|
|
|
d._1
|
|
|
|
|
|
|
|
d._2
|
|
|
|
|
2013-07-29 16:53:55 +04:00
|
|
|
|
2013-07-29 21:33:03 +04:00
|
|
|
|
2013-07-29 16:53:55 +04:00
|
|
|
// Combinators
|
|
|
|
|
|
|
|
s.map(sq)
|
|
|
|
|
|
|
|
val sSquared = s. map(sq)
|
|
|
|
|
|
|
|
sSquared.filter(_ < 10)
|
|
|
|
|
|
|
|
sSquared.reduce (_+_)
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// The filter function takes a predicate (a function from A -> Boolean) and
|
|
|
|
// selects all elements which satisfy the predicate
|
2013-06-30 11:52:21 +04:00
|
|
|
List(1, 2, 3) filter (_ > 2) // List(3)
|
|
|
|
List(
|
|
|
|
Person(name = "Dom", age = 23),
|
|
|
|
Person(name = "Bob", age = 30)
|
|
|
|
).filter(_.age > 25) // List(Person("Bob", 30))
|
|
|
|
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// Scala a foreach method defined on certain collections that takes a type
|
|
|
|
// returning Unit (a void method)
|
2013-06-30 11:52:21 +04:00
|
|
|
aListOfNumbers foreach (x => println(x))
|
|
|
|
aListOfNumbers foreach println
|
|
|
|
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
|
2013-07-29 16:53:55 +04:00
|
|
|
|
|
|
|
// For comprehensions
|
|
|
|
|
|
|
|
for { n <- s } yield sq(n)
|
|
|
|
|
|
|
|
val nSquared2 = for { n <- s } yield sq(n)
|
|
|
|
|
|
|
|
for { n <- nSquared2 if n < 10 } yield n
|
|
|
|
|
|
|
|
for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
/* NB Those were not for loops. The semantics of a for loop is 'repeat', whereas
|
|
|
|
a for-comprehension defines a relationship between two sets of data. */
|
2013-07-29 21:33:03 +04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// Loops and iteration
|
|
|
|
|
|
|
|
1 to 5
|
|
|
|
val r = 1 to 5
|
|
|
|
r.foreach( println )
|
|
|
|
|
|
|
|
r foreach println
|
2013-08-02 20:39:30 +04:00
|
|
|
// NB: Scala is quite lenient when it comes to dots and brackets - study the
|
|
|
|
// rules separately. This helps write DSLs and APIs that read like English
|
2013-07-29 21:33:03 +04:00
|
|
|
|
|
|
|
(5 to 1 by -1) foreach ( println )
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// A while loops
|
2013-07-29 21:33:03 +04:00
|
|
|
var i = 0
|
|
|
|
while (i < 10) { println("i " + i); i+=1 }
|
|
|
|
|
|
|
|
while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why?
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
i // Show the value of i. Note that while is a loop in the classical sense -
|
|
|
|
// it executes sequentially while changing the loop variable. while is very
|
|
|
|
// fast, faster that Java // loops, but using the combinators and
|
|
|
|
// comprehensions above is easier to understand and parallelize
|
2013-07-29 21:33:03 +04:00
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// A do while loop
|
2013-08-02 20:39:30 +04:00
|
|
|
do {
|
2013-08-01 13:11:15 +04:00
|
|
|
println("x is still less then 10");
|
|
|
|
x += 1
|
|
|
|
} while (x < 10)
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// Tail recursion is an idiomatic way of doing recurring things in Scala.
|
|
|
|
// Recursive functions need an explicit return type, the compiler can't infer it.
|
|
|
|
// Here it's Unit.
|
|
|
|
def showNumbersInRange(a:Int, b:Int):Unit = {
|
|
|
|
print(a)
|
|
|
|
if (a < b)
|
|
|
|
showNumbersInRange(a + 1, b)
|
|
|
|
}
|
2013-07-29 21:33:03 +04:00
|
|
|
|
2013-07-29 16:53:55 +04:00
|
|
|
|
|
|
|
|
|
|
|
// Conditionals
|
|
|
|
|
|
|
|
val x = 10
|
|
|
|
|
|
|
|
if (x == 1) println("yeah")
|
|
|
|
if (x == 10) println("yeah")
|
|
|
|
if (x == 11) println("yeah")
|
2013-08-01 13:11:15 +04:00
|
|
|
if (x == 11) println ("yeah") else println("nay")
|
2013-07-29 16:57:44 +04:00
|
|
|
|
|
|
|
println(if (x == 10) "yeah" else "nope")
|
|
|
|
val text = if (x == 10) "yeah" else "nope"
|
|
|
|
|
2013-07-29 21:33:03 +04:00
|
|
|
var i = 0
|
|
|
|
while (i < 10) { println("i " + i); i+=1 }
|
2013-07-29 16:53:55 +04:00
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
|
|
|
|
|
2013-07-29 16:53:55 +04:00
|
|
|
// Object oriented features
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// Classname is Dog
|
|
|
|
class Dog {
|
|
|
|
//A method called bark, returning a String
|
|
|
|
def bark: String = {
|
|
|
|
// the body of the method
|
|
|
|
"Woof, woof!"
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// Classes can contain nearly any other construct, including other classes,
|
|
|
|
// functions, methods, objects, case classes, traits etc.
|
2013-08-01 13:11:15 +04:00
|
|
|
|
2013-07-29 17:09:11 +04:00
|
|
|
|
2013-07-29 21:33:03 +04:00
|
|
|
|
2013-07-29 17:09:11 +04:00
|
|
|
// Case classes
|
|
|
|
|
|
|
|
case class Person(name:String, phoneNumber:String)
|
|
|
|
|
|
|
|
Person("George", "1234") == Person("Kate", "1236")
|
|
|
|
|
|
|
|
|
|
|
|
|
2013-07-29 21:33:03 +04:00
|
|
|
|
2013-07-29 17:09:11 +04:00
|
|
|
// Pattern matching
|
|
|
|
|
2013-07-29 18:18:24 +04:00
|
|
|
val me = Person("George", "1234")
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
me match { case Person(name, number) => {
|
|
|
|
"We matched someone : " + name + ", phone : " + number }}
|
2013-07-29 18:18:24 +04:00
|
|
|
|
|
|
|
me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." }
|
|
|
|
|
|
|
|
me match { case Person("George", number) => "Match"; case _ => "Hm..." }
|
|
|
|
|
|
|
|
me match { case Person("Kate", number) => "Match"; case _ => "Hm..." }
|
|
|
|
|
|
|
|
me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" }
|
|
|
|
|
|
|
|
val kate = Person("Kate", "1234")
|
|
|
|
|
|
|
|
kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" }
|
|
|
|
|
|
|
|
|
2013-07-29 17:09:11 +04:00
|
|
|
|
|
|
|
// Regular expressions
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex
|
2013-07-29 21:33:03 +04:00
|
|
|
|
|
|
|
val email(user, domain) = "henry@zkpr.com"
|
|
|
|
|
|
|
|
"mrbean@pyahoo.com" match {
|
|
|
|
case email(name, domain) => "I know your name, " + name
|
|
|
|
}
|
|
|
|
|
2013-07-29 18:18:24 +04:00
|
|
|
|
|
|
|
|
2013-07-29 17:09:11 +04:00
|
|
|
// Strings
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
"Scala strings are surrounded by double quotes" //
|
|
|
|
'a' // A Scala Char
|
|
|
|
'Single quote strings don't exist' // Error
|
|
|
|
"Strings have the usual Java methods defined on them".length
|
2013-08-02 20:39:30 +04:00
|
|
|
"They also have some extra Scala methods.".reverse
|
|
|
|
|
|
|
|
// Seealso: scala.collection.immutable.StringOps
|
2013-08-01 13:11:15 +04:00
|
|
|
|
2013-07-29 19:03:49 +04:00
|
|
|
println("ABCDEF".length)
|
|
|
|
println("ABCDEF".substring(2, 6))
|
|
|
|
println("ABCDEF".replace("C", "3"))
|
|
|
|
|
|
|
|
val n = 45
|
|
|
|
println(s"We have $n apples")
|
|
|
|
|
|
|
|
val a = Array(11, 9, 6)
|
|
|
|
println(s"My second daughter is ${a(2-1)} years old")
|
|
|
|
|
2013-07-29 21:33:03 +04:00
|
|
|
// Some characters need to be 'escaped', e.g. a double quote inside a string:
|
|
|
|
val a = "They stood outside the \"Rose and Crown\""
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// Triple double-quotes let strings span multiple rows and contain quotes
|
|
|
|
|
2013-07-29 21:33:03 +04:00
|
|
|
val html = """<form id="daform">
|
|
|
|
<p>Press belo', Joe</p>
|
|
|
|
| <input type="submit">
|
|
|
|
</form>"""
|
|
|
|
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
|
|
|
|
// Application structure and organization
|
|
|
|
|
|
|
|
// Importing things
|
|
|
|
import scala.collection.immutable.List
|
|
|
|
|
|
|
|
// Import all "sub packages"
|
|
|
|
import scala.collection.immutable._
|
|
|
|
|
|
|
|
// Import multiple classes in one statement
|
|
|
|
import scala.collection.immutable.{List, Map}
|
|
|
|
|
|
|
|
// Rename an import using '=>'
|
|
|
|
import scala.collection.immutable{ List => ImmutableList }
|
|
|
|
|
|
|
|
// Import all classes, except some. The following excludes Map and Set:
|
|
|
|
import scala.collection.immutable.{Map => _, Set => _, _}
|
|
|
|
|
2013-08-02 20:39:30 +04:00
|
|
|
// Your programs entry point is defined in an scala file using an object, with a
|
|
|
|
// single method, main:
|
2013-08-01 13:11:15 +04:00
|
|
|
object Application {
|
|
|
|
def main(args: Array[String]): Unit = {
|
|
|
|
// stuff goes here.
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Files can contain multiple classes and objects. Compile with scalac
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2013-07-29 19:03:49 +04:00
|
|
|
// Input and output
|
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
// To read a file line by line
|
|
|
|
import scala.io.Source
|
|
|
|
for(line <- Source.fromPath("myfile.txt").getLines())
|
|
|
|
println(line)
|
|
|
|
|
|
|
|
// To write a file use Java's PrintWriter
|
|
|
|
|
2013-07-29 19:03:49 +04:00
|
|
|
|
|
|
|
```
|
|
|
|
|
|
|
|
## Further resources
|
|
|
|
|
|
|
|
[Scala for the impatient](http://horstmann.com/scala/)
|
|
|
|
|
2013-08-08 01:31:49 +04:00
|
|
|
[Twitter Scala school](http://twitter.github.io/scala_school/)
|
2013-07-29 19:03:49 +04:00
|
|
|
|
2013-08-08 01:31:49 +04:00
|
|
|
[The scala documentation](http://docs.scala-lang.org/)
|
|
|
|
|
|
|
|
[Try Scala in your browser](http://scalatutorials.com/tour/)
|
2013-07-29 17:09:11 +04:00
|
|
|
|
2013-08-01 13:11:15 +04:00
|
|
|
Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user)
|
|
|
|
|