From 4f06e456a973a99e15a232cee60a53c9f0bd8ace Mon Sep 17 00:00:00 2001 From: Dominic Bou-Samra Date: Sun, 30 Jun 2013 17:52:21 +1000 Subject: Started on Scala --- scala.html.markdown | 178 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 178 insertions(+) create mode 100644 scala.html.markdown (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown new file mode 100644 index 00000000..e8cde611 --- /dev/null +++ b/scala.html.markdown @@ -0,0 +1,178 @@ +--- +language: scala +author: Dominic Bou-Samra +author_url: http://dbousamra.github.com +filename: learnscala.scala +--- + +Scala is a + +```scala + +/////////////////////////////////////// +// Basic syntax +/////////////////////////////////////// + +// Single line comments start with two forward slashes +/* +Multi line comments look like this. +*/ + +// Import packages +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 => _, _} + +// Your programs entry point is defined in an scala file using an object, with a single method, main: +object Application { + def main(args: Array[String]): Unit = { + // stuff goes here. + } +} + +// 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 +// val declarations are immutable, whereas var's are mutable. Immutablility is a good thing. +val x = 10 // x is now 10 +x = 20 // error: reassignment to val +var x = 10 +x = 20 // x is now 20 + +/////////////////////////////////////// +// Types +/////////////////////////////////////// + +// Almost all types are objects. + +// You have numbers +3 //3 + +// Math is as per usual +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 + +// Boolean values +true +false + +// Boolean operations +!true // false +!false // true +true == false // false +10 > 5 // true + +// Strings and characters +"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 +"They also have some extra Scala methods.".reverse // See scala.collection.immutable.StringOps + +/////////////////////////////////////// +// Basic control constructs +/////////////////////////////////////// + +// if statements (else statements are optional) +if (10 > 5) println("10 is greater than 5") +// an else +if (x > 5) println("x is greater than 5") +else println("No it's not.") + +// Iteration + +// A while loop +while (x < 10) { + println("x is still less then 10") + x += 1 +} + +// A do while loop +do { + println("x is still less then 10"); + x += 1 +} while (x < 10) + +// A for loop +for (x <- 0 until 10) { + println(x) +} + +// Any object implementing the map/filter/flatMap methods allows the use of a for loop: +val aListOfNumbers: List[Int] = List(1, 2, 3) +for (x <- aListOfNumbers) { + println(x) +} + +// Pattern matching (see respective section) +x match { + case 5 => println("x is 5") + case 10 => println("x is 10") + case _ => println("default case") +} + +/////////////////////////////////////// +// Functions, methods and classes +/////////////////////////////////////// + +// Scala has classes + +// classname is Dog +class Dog { + //A method called bark, returning a String + def bark: String = { + // the body of the method + "Woof, woof!" + } +} + +// They can contain nearly any other construct, including other classes, functions, methods, objects, case classes, traits etc. + +/////////////////////////////////////// +// Higher-order functions +/////////////////////////////////////// + +// Scala allows methods and functions to return, or take as parameters, other functions or methods. + +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) + +// And the underscore symbol, can be used if there is just one argument to the anonymous function. It gets bound as the variable +List(1, 2, 3) map (_ + 10) + +TODO // If the anonymous block AND the function you are applying both take one argument, you can even omit the underscore +List("Dom", "Bob", "Natalia") foreach println + + +// Scala collections have rich higher-order functions defined on them. Some examples: + +// The map function takes a function/method, and applies it to each element in the structure +List(1, 2, 3) map (number => number.toString) + +// The filter function takes a predicate (a function from A -> Boolean) and selects all elements which satisfy the predicate +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)) + + +// Scala a foreach method defined on certain collections that takes a type returning Unit (a void method) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + + -- cgit v1.2.3 From 2e7c3ba085da91a198f7b339d57bdf1fd8c8b49c Mon Sep 17 00:00:00 2001 From: George Petrov Date: Sun, 28 Jul 2013 20:52:32 +0100 Subject: Starting a Scala one --- scala.html.markdown | 53 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 scala.html.markdown (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown new file mode 100644 index 00000000..f087881a --- /dev/null +++ b/scala.html.markdown @@ -0,0 +1,53 @@ +/* + 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> + + This is the so called REPL. You can run commands in the REPL. Let do just that: +*/ + +println(10) // prints the integer 10 + +println("Boo!") // printlns the string Boo! + + +// Evaluating a command gives you the type and value of the result + +1 + 7 + +/* The above line results in: + + scala> 1 + 7 + res29: Int = 8 + + This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 + + 1+7 will give you the same result +*/ + + +// Everything is an object, including a function type these in the repl: + +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 = + + Which means that this time we gave an explicit name to the value - sq is a function that take an Int and returns Int. + + sq can be executed as follows: +*/ + +sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 + -- cgit v1.2.3 From 7673ae8a6dc79fdc8f555d8e0c64834af17403d1 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 09:29:14 +0100 Subject: Added arrays and maps --- scala.html.markdown | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index f087881a..82bf9db2 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -51,3 +51,16 @@ val sq = (x:Int) => x * x sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 + + +// 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") +m("bottle") // Throws an exception \ No newline at end of file -- cgit v1.2.3 From 04e50a75fa253f71cf5de0f45d423f06dd9933d2 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 13:53:55 +0100 Subject: Added for comprehensions and conditionals --- scala.html.markdown | 48 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 82bf9db2..783c7ae6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -63,4 +63,50 @@ a(21) // Throws an exception val m = Map("fork" -> "tenedor", "spoon" -> "cuchara", "knife" -> "cuchillo") m("fork") m("spoon") -m("bottle") // Throws an exception \ No newline at end of file +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + + +// Tuples + + +// Combinators + +s.map(sq) + +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + + +// 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 + + + +// Conditionals + +val x = 10 + +if (x == 1) println("yeah") +if (x == 10) println("yeah") +if (x == 11) println("yeah") + + +// Object oriented features + -- cgit v1.2.3 From 3cc4c64fb75581a21a2d8d4c2a28f3e83b5cf2f7 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 13:57:44 +0100 Subject: Added header --- scala.html.markdown | 11 +++++++++++ 1 file changed, 11 insertions(+) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 783c7ae6..173d271d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,3 +1,9 @@ +--- +language: scala +author: George Petrov +author_url: http://www.georgepetrov.com +--- + /* Set yourself up: @@ -106,6 +112,11 @@ val x = 10 if (x == 1) println("yeah") if (x == 10) println("yeah") if (x == 11) println("yeah") +if (x == 11) println ("yeah") else println("nope") + +println(if (x == 10) "yeah" else "nope") +val text = if (x == 10) "yeah" else "nope" + // Object oriented features -- cgit v1.2.3 From d346342ad608849bdd1bcae7973bbff571225ba1 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 14:09:11 +0100 Subject: Added some pattern matching --- scala.html.markdown | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 173d271d..d6524a8f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -121,3 +121,25 @@ val text = if (x == 10) "yeah" else "nope" // Object oriented features +class Person + + + +// Case classes + +case class Person(name:String, phoneNumber:String) + +Person("George", "1234") == Person("Kate", "1236") + + + +// Pattern matching + + +// Regular expressions + + +// Strings + + +// Input and output \ No newline at end of file -- cgit v1.2.3 From 33f3d4d6953cce6c45f2a7f4e8afc12571193c73 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 15:14:37 +0100 Subject: Fixing formatting --- scala.html.markdown | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index d6524a8f..3aedc88a 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,9 +1,16 @@ --- language: scala +filename: learn.scala author: George Petrov -author_url: http://www.georgepetrov.com +author_url: http://www.github.com/petrovg --- +Scala - the scalable language + +```c + + + /* Set yourself up: -- cgit v1.2.3 From 99b16c2672a2fc0b1dbb063c0b6e066158922099 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 15:18:24 +0100 Subject: Now really adding some pattern matching --- scala.html.markdown | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index d6524a8f..d0187667 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -135,10 +135,29 @@ Person("George", "1234") == Person("Kate", "1236") // Pattern matching +val me = Person("George", "1234") + +me match { case Person(name, number) => "We matched someone : " + name + ", phone : " + number } + +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" } + + // Regular expressions + + // Strings -- cgit v1.2.3 From 3f2922d87a1c947eb6e20551846fd1b307984680 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 16:03:49 +0100 Subject: Adding some strings and docs links --- scala.html.markdown | 33 ++++++++++++++++++++++++++++----- 1 file changed, 28 insertions(+), 5 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 8c000177..a1396b4d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -85,6 +85,10 @@ val s = Set(1, 3, 7) s(0) s(1) +/* Look up the documentation of map here - http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + // Tuples @@ -128,9 +132,6 @@ val text = if (x == 10) "yeah" else "nope" // Object oriented features -class Person - - // Case classes @@ -162,10 +163,32 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions - +// TODO // Strings +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") + +// Input and output + + +``` + +## Further resources + +[Scala for the impatient](http://horstmann.com/scala/) + +[Twitter Scala school(http://twitter.github.io/scala_school/) + +[The scala documentation] -// Input and output \ No newline at end of file +Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) \ No newline at end of file -- cgit v1.2.3 From a6ec23d414ba495b26a4028f9a6795d18a02cdac Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 18:33:03 +0100 Subject: Added loops, iterators and regex --- scala.html.markdown | 56 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index a1396b4d..8bcbc27f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -93,6 +93,7 @@ s(1) // Tuples + // Combinators s.map(sq) @@ -114,6 +115,37 @@ for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared +/* 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. Research this further */ + + + +// Loops and iteration + +1 to 5 +val r = 1 to 5 +r.foreach( println ) + +r foreach println +// NB: Scala is quite lenien when it comes to dots and brackets - study the rules separately. This +// helps write DSLs and APIs that read like English + +(5 to 1 by -1) foreach ( println ) + +var i = 0 +while (i < 10) { println("i " + i); i+=1 } + +while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? + +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 + +// Tail recursion is an idiomatic way of doing things in Scala. Recursive functions need an +// explicit return type, the compile can't infer it. Here it's Unit. +def showNumbersInRange(a:Int, b:Int):Unit = { print(a); if (a < b) showNumbersInRange(a+1, b) } + // Conditionals @@ -128,11 +160,13 @@ if (x == 11) println ("yeah") else println("nope") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" - +var i = 0 +while (i < 10) { println("i " + i); i+=1 } // Object oriented features + // Case classes case class Person(name:String, phoneNumber:String) @@ -141,6 +175,7 @@ Person("George", "1234") == Person("Kate", "1236") + // Pattern matching val me = Person("George", "1234") @@ -163,7 +198,14 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions -// TODO +val email = "(.*)@(.*)".r // The suffix .r invokes method r on String, which makes it a Regex + +val email(user, domain) = "henry@zkpr.com" + +"mrbean@pyahoo.com" match { + case email(name, domain) => "I know your name, " + name +} + // Strings @@ -178,6 +220,16 @@ println(s"We have $n apples") val a = Array(11, 9, 6) println(s"My second daughter is ${a(2-1)} years old") +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" + +// Triple double-quotes allow for strings to span multiple rows and contain funny characters +val html = """
+

Press belo', Joe

+ | +
""" + + // Input and output -- cgit v1.2.3 From 8235ddc50fce389356bc9ebb9e1b7249fa8bd5e7 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 22:19:15 +0100 Subject: Fixing a typo --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 8bcbc27f..57706c1f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -20,7 +20,7 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let do just that: + This is the so called REPL. You can run commands in the REPL. Let's do just that: */ println(10) // prints the integer 10 -- cgit v1.2.3 From 82a5e4c8f0b3d79a2797fa0b5cdaf962bd7b3bf4 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 23:59:12 +0100 Subject: Fixed header --- scala.html.markdown | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 57706c1f..e7a432f6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,8 +1,7 @@ --- -language: scala +language: Scala filename: learn.scala -author: George Petrov -author_url: http://www.github.com/petrovg +contributors:["George Petrov", "http://github.com/petrovg"] --- Scala - the scalable language @@ -43,7 +42,7 @@ println("Boo!") // printlns the string Boo! */ -// Everything is an object, including a function type these in the repl: +// Everything is an object, including a function. Type these in the REPL: 7 // results in res30: Int = 7 (res30 is just a generated var name for the result) -- cgit v1.2.3 From 11edf04311e33fad32c0bc943980482433b63460 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Mon, 29 Jul 2013 23:59:58 +0100 Subject: Tweaking the header --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index e7a432f6..49c7bb14 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,7 +1,7 @@ --- language: Scala filename: learn.scala -contributors:["George Petrov", "http://github.com/petrovg"] +contributors: ["George Petrov", "http://github.com/petrovg"] --- Scala - the scalable language -- cgit v1.2.3 From 49ee527a79adbe3fde50b71effb4a9340b7ab7dc Mon Sep 17 00:00:00 2001 From: George Petrov Date: Tue, 30 Jul 2013 00:03:28 +0100 Subject: Header messages --- scala.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 49c7bb14..b22ba15b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,7 +1,8 @@ --- language: Scala +contributors: + - ["George Petrov", "http://github.com/petrovg"] filename: learn.scala -contributors: ["George Petrov", "http://github.com/petrovg"] --- Scala - the scalable language -- cgit v1.2.3 From 38bd9a18fda39e70060cd64a49a0095ba4901e26 Mon Sep 17 00:00:00 2001 From: George Petrov Date: Wed, 31 Jul 2013 20:52:59 +0100 Subject: Added tuples --- scala.html.markdown | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index b22ba15b..8bcb5975 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -92,6 +92,26 @@ s(1) // Tuples +(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 + +// To access the elements of a tuple, use _._n where n is the 1-based index of the element +val d = divideInts(10,3) + +d._1 + +d._2 + // Combinators -- cgit v1.2.3 From 906c7164d0975d14da0391ff47b5c384f0dd1c47 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 2 Aug 2013 09:39:30 -0700 Subject: Updated scala for line lengths --- scala.html.markdown | 86 +++++++++++++++++++++++++++++++++-------------------- 1 file changed, 53 insertions(+), 33 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 8e00f135..687914ef 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -8,9 +8,7 @@ filename: learn.scala Scala - the scalable language -```c - - +```scala /* Set yourself up: @@ -21,7 +19,8 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let's do just that: + This is the so called REPL. You can run commands in the REPL. Let's do just + that: */ println(10) // prints the integer 10 @@ -37,7 +36,8 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutablility is a good thing. +// val declarations are immutable, whereas var's are mutable. Immutablility is +// a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val var x = 10 @@ -74,7 +74,8 @@ true == false // false scala> 1 + 7 res29: Int = 8 - This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 + This means the result of evaluating 1 + 7 is an object of type Int with a + value of 8 1+7 will give you the same result */ @@ -94,14 +95,16 @@ val sq = (x:Int) => x * x sq: Int => Int = - Which means that this time we gave an explicit name to the value - sq is a function that take an Int and returns Int. + Which means that this time we gave an explicit name to the value - sq is a + function that take an Int and returns Int. sq can be executed as follows: */ -sq(10) // Gives you this: res33: Int = 100. The result is the Int with a value 100 +sq(10) // Gives you this: res33: Int = 100. -// Scala allows methods and functions to return, or take as parameters, other functions or methods. +// Scala allows methods and functions to return, or take as parameters, other +// functions or methods. 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 @@ -109,10 +112,12 @@ 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) -// And the underscore symbol, can be used if there is just one argument to the anonymous function. It gets bound as the variable +// And the underscore symbol, can be used if there is just one argument to the +// anonymous function. It gets bound as the variable List(1, 2, 3) map (_ + 10) -TODO // If the anonymous block AND the function you are applying both take one argument, you can even omit the underscore +// If the anonymous block AND the function you are applying both take one +// argument, you can even omit the underscore List("Dom", "Bob", "Natalia") foreach println @@ -136,7 +141,8 @@ val s = Set(1, 3, 7) s(0) s(1) -/* Look up the documentation of map here - http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map +/* Look up the documentation of map here - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map * and make sure you can read it */ @@ -156,7 +162,8 @@ val divideInts = (x:Int, y:Int) => (x / y, x % y) divideInts(10,3) // The function divideInts gives you the result and the remainder -// To access the elements of a tuple, use _._n where n is the 1-based index of the element +// To access the elements of a tuple, use _._n where n is the 1-based index of +// the element val d = divideInts(10,3) d._1 @@ -175,7 +182,8 @@ sSquared.filter(_ < 10) sSquared.reduce (_+_) -// The filter function takes a predicate (a function from A -> Boolean) and selects all elements which satisfy the predicate +// The filter function takes a predicate (a function from A -> Boolean) and +// selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) List( Person(name = "Dom", age = 23), @@ -183,7 +191,8 @@ List( ).filter(_.age > 25) // List(Person("Bob", 30)) -// Scala a foreach method defined on certain collections that takes a type returning Unit (a void method) +// Scala a foreach method defined on certain collections that takes a type +// returning Unit (a void method) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -200,8 +209,8 @@ for { n <- nSquared2 if n < 10 } yield n for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared -/* 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. Research this further */ +/* 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. */ @@ -212,8 +221,8 @@ val r = 1 to 5 r.foreach( println ) r foreach println -// NB: Scala is quite lenien when it comes to dots and brackets - study the rules separately. This -// helps write DSLs and APIs that read like English +// 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 (5 to 1 by -1) foreach ( println ) @@ -223,20 +232,25 @@ while (i < 10) { println("i " + i); i+=1 } while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? -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 +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 // A do while loop -do { +do { println("x is still less then 10"); x += 1 } while (x < 10) -// 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) } +// 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) +} @@ -268,7 +282,8 @@ class Dog { } } -// Classes can contain nearly any other construct, including other classes, functions, methods, objects, case classes, traits etc. +// Classes can contain nearly any other construct, including other classes, +// functions, methods, objects, case classes, traits etc. @@ -285,7 +300,8 @@ Person("George", "1234") == Person("Kate", "1236") val me = Person("George", "1234") -me match { case Person(name, number) => "We matched someone : " + name + ", phone : " + number } +me match { case Person(name, number) => { + "We matched someone : " + name + ", phone : " + number }} me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } @@ -303,7 +319,7 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions -val email = "(.*)@(.*)".r // The suffix .r invokes method r on String, which makes it a Regex +val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex val email(user, domain) = "henry@zkpr.com" @@ -319,7 +335,9 @@ val email(user, domain) = "henry@zkpr.com" 'a' // A Scala Char 'Single quote strings don't exist' // Error "Strings have the usual Java methods defined on them".length -"They also have some extra Scala methods.".reverse // See scala.collection.immutable.StringOps +"They also have some extra Scala methods.".reverse + +// Seealso: scala.collection.immutable.StringOps println("ABCDEF".length) println("ABCDEF".substring(2, 6)) @@ -334,7 +352,8 @@ println(s"My second daughter is ${a(2-1)} years old") // Some characters need to be 'escaped', e.g. a double quote inside a string: val a = "They stood outside the \"Rose and Crown\"" -// Triple double-quotes allow for strings to span multiple rows and contain funny characters +// Triple double-quotes let strings span multiple rows and contain quotes + val html = """

Press belo', Joe

| @@ -359,7 +378,8 @@ import scala.collection.immutable{ List => ImmutableList } // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -// Your programs entry point is defined in an scala file using an object, with a single method, main: +// Your programs entry point is defined in an scala file using an object, with a +// single method, main: object Application { def main(args: Array[String]): Unit = { // stuff goes here. -- cgit v1.2.3 From 9d2c808fcb7a8226868778fa4f2403266178dc06 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 2 Aug 2013 09:43:54 -0700 Subject: corrected scala --- scala.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 687914ef..a5920aa8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -1,8 +1,9 @@ --- language: Scala +filename: learnscala.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - - ["Dominic Bou-Samra, "http://dbousamra.github.com"] + - ["Dominic Bou-Samra", "http://dbousamra.github.com"] filename: learn.scala --- -- cgit v1.2.3 From 22f1469dd8092ff46a73e27b56363f7c922ac875 Mon Sep 17 00:00:00 2001 From: Adam Date: Fri, 2 Aug 2013 09:47:13 -0700 Subject: Used c syntax highlighting for scala for now --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index a5920aa8..fef09404 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -9,7 +9,7 @@ filename: learn.scala Scala - the scalable language -```scala +```cpp /* Set yourself up: -- cgit v1.2.3 From bd2a852ae827a979f2170f90d6bd7bca4ef7c084 Mon Sep 17 00:00:00 2001 From: Eran Medan Date: Wed, 7 Aug 2013 17:31:49 -0400 Subject: fixed some broken / missing markdown links and added a resource --- scala.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index fef09404..b1b3ecbf 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -408,9 +408,11 @@ for(line <- Source.fromPath("myfile.txt").getLines()) [Scala for the impatient](http://horstmann.com/scala/) -[Twitter Scala school(http://twitter.github.io/scala_school/) +[Twitter Scala school](http://twitter.github.io/scala_school/) -[The scala documentation] +[The scala documentation](http://docs.scala-lang.org/) + +[Try Scala in your browser](http://scalatutorials.com/tour/) Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From c9587395d279c538f94e672b154e15f8b9f92e5b Mon Sep 17 00:00:00 2001 From: Matthieu Moquet Date: Sat, 28 Sep 2013 15:33:32 +0200 Subject: =?UTF-8?q?[Scala]=C2=A0Fix=20typo:=20forgotten=20dot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index b1b3ecbf..03c1ea76 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -374,7 +374,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // Rename an import using '=>' -import scala.collection.immutable{ List => ImmutableList } +import scala.collection.immutable.{ List => ImmutableList } // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -- cgit v1.2.3 From c0a9eabb6c6780c6ab1a9501a6aa2bc49b2dd54c Mon Sep 17 00:00:00 2001 From: Cengiz Can Date: Mon, 30 Dec 2013 09:45:15 +0200 Subject: Source.fromPath no longer exists (https://github.com/scala/scala/blob/master/src/library/scala/io/Source.scala) Changed example to use Source.fromFile --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 03c1ea76..5dfaefe0 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -396,7 +396,7 @@ object Application { // To read a file line by line import scala.io.Source -for(line <- Source.fromPath("myfile.txt").getLines()) +for(line <- Source.fromFile("myfile.txt").getLines()) println(line) // To write a file use Java's PrintWriter -- cgit v1.2.3 From bd6d3be775fd6be55f92d1d368b303f40618c0e1 Mon Sep 17 00:00:00 2001 From: rostdotio Date: Fri, 28 Feb 2014 10:31:10 +0100 Subject: Added explanation for colon character Use of the colon character for value assignment is now explained by example of function add10. --- scala.html.markdown | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 5dfaefe0..2666746e 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -104,10 +104,13 @@ val sq = (x:Int) => x * x sq(10) // Gives you this: res33: Int = 100. +// The colon explicitly defines the type of a value, in this case a function +// taking an Int and returning an Int. +val add10: Int => Int = _ + 10 + // Scala allows methods and functions to return, or take as parameters, other // functions or methods. -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: -- cgit v1.2.3 From 73195400ba731c43365078023db792ab23bca1d6 Mon Sep 17 00:00:00 2001 From: Duncan Beaton Date: Sun, 6 Jul 2014 20:10:15 +0100 Subject: Fix 'Immutability' typo --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 2666746e..432933c2 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -37,7 +37,7 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutablility is +// val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -- cgit v1.2.3 From 3cb8d2bcc56332a814d0ae69492782ee4ddbd473 Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Fri, 8 Aug 2014 15:19:14 +0200 Subject: - [ADD] PrintWriter example from Java - [CHANGE] Extended regex matching with more examples with switch / case - [CHANGE] String interpolation with formatting and expressions explained. --- scala.html.markdown | 39 +++++++++++++++++++++++++++++---------- 1 file changed, 29 insertions(+), 10 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 432933c2..4dc87a94 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -299,7 +299,6 @@ Person("George", "1234") == Person("Kate", "1236") - // Pattern matching val me = Person("George", "1234") @@ -322,15 +321,22 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions - val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex - -val email(user, domain) = "henry@zkpr.com" - -"mrbean@pyahoo.com" match { - case email(name, domain) => "I know your name, " + name +val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using multiline string syntax + +val matcher = (value: String) => { + println(value match { + case email(name, domain) => s"It was an email: $name" + case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" + case _ => s"No match on '$value'" // default if no match found + }) } +matcher("mrbean@pyahoo.com") +matcher("nope..") +matcher("52917") +matcher("52752-16432-22178-47917") + // Strings @@ -347,17 +353,27 @@ println("ABCDEF".length) println("ABCDEF".substring(2, 6)) println("ABCDEF".replace("C", "3")) +// String interpolation val n = 45 println(s"We have $n apples") +// Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(2-1)} years old") +println(s"My second daughter is ${a(0) - a(2)} years old") +println(s"We have double the amount of ${n / 2.0} in apples.") +println(s"Power of 2: ${math.pow(2, 2)}") // Power of 2: 4.0 + +// Formatting with interpolated strings (note the prefixed f) +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // Power of 5: 25 +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // Square root of 122 + +// Ignoring special characters. +println(raw"New line feed: \n. Carriage return: \r.") // Some characters need to be 'escaped', e.g. a double quote inside a string: val a = "They stood outside the \"Rose and Crown\"" // Triple double-quotes let strings span multiple rows and contain quotes - val html = """

Press belo', Joe

| @@ -403,7 +419,10 @@ for(line <- Source.fromFile("myfile.txt").getLines()) println(line) // To write a file use Java's PrintWriter - +val writer = new PrintWriter("myfile.txt") +writer.write("Writing line for line" + util.Properties.lineSeparator) +writer.write("Another line here" + util.Properties.lineSeparator) +writer.close() ``` -- cgit v1.2.3 From 07b6229ee608ae37283a827112b5eab4c58a5333 Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Fri, 8 Aug 2014 15:23:46 +0200 Subject: [CHANGE] Comment match on serial key now mentions verbatim (multiline) --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 4dc87a94..619c8aae 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -322,7 +322,7 @@ kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" // Regular expressions val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex -val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using multiline string syntax +val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax val matcher = (value: String) => { println(value match { -- cgit v1.2.3 From d2cf0062822ec364a21afa6550d4d0538857a7fe Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Fri, 15 Aug 2014 15:47:12 +0200 Subject: [CHANGE] Output examples added to matcher part and string interpolation part. --- scala.html.markdown | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 619c8aae..eae39abb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -332,11 +332,10 @@ val matcher = (value: String) => { }) } -matcher("mrbean@pyahoo.com") -matcher("nope..") -matcher("52917") -matcher("52752-16432-22178-47917") - +matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" +matcher("nope..") // => "No match on 'nope..'" +matcher("52917") // => "No match on '52917'" +matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" // Strings @@ -359,13 +358,13 @@ println(s"We have $n apples") // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old") -println(s"We have double the amount of ${n / 2.0} in apples.") -println(s"Power of 2: ${math.pow(2, 2)}") // Power of 2: 4.0 +println(s"My second daughter is ${a(0) - a(2)} years old") // => "My second daughter is 5 years old" +println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." +println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" // Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // Power of 5: 25 -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // Square root of 122 +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" // Ignoring special characters. println(raw"New line feed: \n. Carriage return: \r.") -- cgit v1.2.3 From 775c7faa65e84b8030478f4476995935ac8c2813 Mon Sep 17 00:00:00 2001 From: "a.vandijk" Date: Sat, 16 Aug 2014 18:21:49 +0200 Subject: [ADDED] Output to additional println's. --- scala.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index eae39abb..6b398b4b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -354,11 +354,11 @@ println("ABCDEF".replace("C", "3")) // String interpolation val n = 45 -println(s"We have $n apples") +println(s"We have $n apples") // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old") // => "My second daughter is 5 years old" +println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" @@ -367,10 +367,10 @@ println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" // Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") +println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." // Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" +val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" // Triple double-quotes let strings span multiple rows and contain quotes val html = """ -- cgit v1.2.3 From 3771906a8c93eeca9333189db5cf3374c69e085a Mon Sep 17 00:00:00 2001 From: Michael Bock Date: Mon, 25 Aug 2014 00:13:59 -0700 Subject: Fix typo in scala "less then" -> "less than" --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 6b398b4b..379c092c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -243,7 +243,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less then 10"); + println("x is still less than 10"); x += 1 } while (x < 10) -- cgit v1.2.3 From eab554a7a7f2869ff7dac9f54acce9a7ed55cfa4 Mon Sep 17 00:00:00 2001 From: Adam Date: Mon, 8 Sep 2014 13:08:28 +0200 Subject: Review docs for added rouge lexers and update those with new highlighters --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 379c092c..5a0cc0ff 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -9,7 +9,7 @@ filename: learn.scala Scala - the scalable language -```cpp +```scala /* Set yourself up: -- cgit v1.2.3 From af29a504c0eb02e9eb575d5cace38676f7cf1ef1 Mon Sep 17 00:00:00 2001 From: Bonnie Barrilleaux Date: Wed, 5 Nov 2014 14:06:34 -0800 Subject: Added a few clarifying lines to Scala so that the examples can be run as given. Removed a duplicate example. --- scala.html.markdown | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 5a0cc0ff..201a51ab 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -189,6 +189,8 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) + +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -197,6 +199,7 @@ List( // Scala a foreach method defined on certain collections that takes a type // returning Unit (a void method) +val aListOfNumbers = Set(1,2,3,45,234) aListOfNumbers foreach (x => println(x)) aListOfNumbers foreach println @@ -255,6 +258,7 @@ def showNumbersInRange(a:Int, b:Int):Unit = { if (a < b) showNumbersInRange(a + 1, b) } +showNumbersInRange(1,14) @@ -270,15 +274,13 @@ if (x == 11) println ("yeah") else println("nay") println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -var i = 0 -while (i < 10) { println("i " + i); i+=1 } - // Object oriented features // Classname is Dog -class Dog { +class Dog (br: String) { + var breed: String = br //A method called bark, returning a String def bark: String = { // the body of the method @@ -286,6 +288,11 @@ class Dog { } } +val mydog = new Dog("greyhound") +println(mydog.breed) // => "greyhound" +println(mydog.bark) // => "Woof, woof!" + + // Classes can contain nearly any other construct, including other classes, // functions, methods, objects, case classes, traits etc. -- cgit v1.2.3 From a32a8e140153d5ffd341bb38515660f80da37575 Mon Sep 17 00:00:00 2001 From: Bonnie Date: Thu, 6 Nov 2014 18:47:38 -0800 Subject: Remove an extraneous space. --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 201a51ab..775956cb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -279,7 +279,7 @@ val text = if (x == 10) "yeah" else "nope" // Object oriented features // Classname is Dog -class Dog (br: String) { +class Dog(br: String) { var breed: String = br //A method called bark, returning a String def bark: String = { -- cgit v1.2.3 From 57c9f704170cd4d3adf49623c9f1b7a7a9670925 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:24:00 -0700 Subject: A huge re-organization of the Scala file --- scala.html.markdown | 358 ++++++++++++++++++++++++++++------------------------ 1 file changed, 193 insertions(+), 165 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 5a0cc0ff..a55e1f0e 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -4,6 +4,7 @@ filename: learnscala.scala contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] + - ["Geoff Liu", "http://geoffliu.me"] filename: learn.scala --- @@ -20,16 +21,16 @@ Scala - the scalable language scala> - This is the so called REPL. You can run commands in the REPL. Let's do just - that: + This is the so called REPL (Read-Eval-Print Loop). You may type any valid + Scala expression into it, and the result will be printed. We will explain what + Scala files look like further into this tutorial, but for now, let's start + with some basics. */ -println(10) // prints the integer 10 -println("Boo!") // printlns the string Boo! - - -// Some basics +################################################# +## 1. Basics +################################################# // Printing, and forcing a new line on the next print println("Hello world!") @@ -37,15 +38,15 @@ println("Hello world!") print("Hello world") // Declaring values is done using either var or val -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -var x = 10 +var x = 10 x = 20 // x is now 20 // Single line comments start with two forward slashes -/* +/* Multi line comments look like this. */ @@ -82,149 +83,83 @@ true == false // false */ -// Everything is an object, including a function. Type these in the REPL: - -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 = - - Which means that this time we gave an explicit name to the value - sq is a - function that take an Int and returns Int. - - sq can be executed as follows: -*/ - -sq(10) // Gives you this: res33: Int = 100. - -// The colon explicitly defines the type of a value, in this case a function -// taking an Int and returning an Int. -val add10: Int => Int = _ + 10 - -// Scala allows methods and functions to return, or take as parameters, other -// functions or methods. - -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) - -// And the underscore symbol, can be used if there is just one argument to the -// anonymous function. It gets bound as the variable -List(1, 2, 3) map (_ + 10) - -// If the anonymous block AND the function you are applying both take one -// argument, you can even omit the underscore -List("Dom", "Bob", "Natalia") foreach println - - - -// 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") -m("bottle") // Throws an exception - -val safeM = m.withDefaultValue("no lo se") -safeM("bottle") - -val s = Set(1, 3, 7) -s(0) -s(1) - -/* Look up the documentation of map here - - * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map - * and make sure you can read it - */ - - -// Tuples - -(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 - -// To access the elements of a tuple, use _._n where n is the 1-based index of -// the element -val d = divideInts(10,3) - -d._1 - -d._2 - +// Strings +"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 +"They also have some extra Scala methods.".reverse -// Combinators +// Seealso: scala.collection.immutable.StringOps -s.map(sq) +println("ABCDEF".length) +println("ABCDEF".substring(2, 6)) +println("ABCDEF".replace("C", "3")) -val sSquared = s. map(sq) +// String interpolation +val n = 45 +println(s"We have $n apples") // => "We have 45 apples" -sSquared.filter(_ < 10) +// Expressions inside interpolated strings are also possible +val a = Array(11, 9, 6) +println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." +println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." +println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" -sSquared.reduce (_+_) +// Formatting with interpolated strings (note the prefixed f) +println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" +println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" -// The filter function takes a predicate (a function from A -> Boolean) and -// selects all elements which satisfy the predicate -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)) +// Ignoring special characters. +println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Some characters need to be 'escaped', e.g. a double quote inside a string: +val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" -// Scala a foreach method defined on certain collections that takes a type -// returning Unit (a void method) -aListOfNumbers foreach (x => println(x)) -aListOfNumbers foreach println +// Triple double-quotes let strings span multiple rows and contain quotes +val html = """ +

Press belo', Joe

+ | + """ +################################################# +## 2. Functions +################################################# +// The next line gives you a function that takes an Int and returns it squared +(x:Int) => x * x -// For comprehensions +// You can assign this function to an identifier, like this: +val sq = (x:Int) => x * x -for { n <- s } yield sq(n) +/* The above says this -val nSquared2 = for { n <- s } yield sq(n) + sq: Int => Int = -for { n <- nSquared2 if n < 10 } yield n + Which means that this time we gave an explicit name to the value - sq is a + function that take an Int and returns Int. -for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared + sq can be executed as follows: +*/ -/* 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. */ +sq(10) // Gives you this: res33: Int = 100. +// The colon explicitly defines the type of a value, in this case a function +// taking an Int and returning an Int. +val add10: Int => Int = _ + 10 -// Loops and iteration +################################################# +## 3. Flow Control +################################################# 1 to 5 val r = 1 to 5 r.foreach( println ) -r foreach println +r foreach println // 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 @@ -243,7 +178,7 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less than 10"); + println("x is still less than 10"); x += 1 } while (x < 10) @@ -257,7 +192,6 @@ def showNumbersInRange(a:Int, b:Int):Unit = { } - // Conditionals val x = 10 @@ -274,10 +208,76 @@ var i = 0 while (i < 10) { println("i " + i); i+=1 } +################################################# +## 4. Data Structures +################################################# -// Object oriented features +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") +m("bottle") // Throws an exception + +val safeM = m.withDefaultValue("no lo se") +safeM("bottle") + +val s = Set(1, 3, 7) +s(0) +s(1) + +/* Look up the documentation of map here - + * http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Map + * and make sure you can read it + */ + + +// Tuples + +(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 + +// To access the elements of a tuple, use _._n where n is the 1-based index of +// the element +val d = divideInts(10,3) + +d._1 + +d._2 + + +################################################# +## 5. Object Oriented Programming +################################################# + +/* + Aside: Everything we've done so far in this tutorial has been simple + expressions (values, functions, etc). These expressions are fine to type into + the command-line interpreter for quick tests, but they cannot exist by + themselves in a Scala file. For example, you cannot have just "val x = 5" in + a Scala file. Instead, the only top-level constructs allowed in Scala are: + + - objects + - classes + - case classes + - traits + + And now we will explain what these are. +*/ -// Classname is Dog class Dog { //A method called bark, returning a String def bark: String = { @@ -289,8 +289,6 @@ class Dog { // Classes can contain nearly any other construct, including other classes, // functions, methods, objects, case classes, traits etc. - - // Case classes case class Person(name:String, phoneNumber:String) @@ -298,8 +296,12 @@ case class Person(name:String, phoneNumber:String) Person("George", "1234") == Person("Kate", "1236") +// Objects and traits coming soon! + -// Pattern matching +################################################# +## 6. Pattern Matching +################################################# val me = Person("George", "1234") @@ -338,49 +340,75 @@ matcher("52917") // => "No match on '52917'" matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" -// Strings +################################################# +## 7. Functional Programming +################################################# -"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 -"They also have some extra Scala methods.".reverse +// Scala allows methods and functions to return, or take as parameters, other +// functions or methods. -// Seealso: scala.collection.immutable.StringOps +List(1, 2, 3) map add10 // List(11, 12, 13) - add10 is applied to each element -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// Anonymous functions can be used instead of named functions: +List(1, 2, 3) map (x => x + 10) -// String interpolation -val n = 45 -println(s"We have $n apples") // => "We have 45 apples" +// And the underscore symbol, can be used if there is just one argument to the +// anonymous function. It gets bound as the variable +List(1, 2, 3) map (_ + 10) -// Expressions inside interpolated strings are also possible -val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." -println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." -println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" +// If the anonymous block AND the function you are applying both take one +// argument, you can even omit the underscore +List("Dom", "Bob", "Natalia") foreach println -// Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" -// Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Combinators -// Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +s.map(sq) -// Triple double-quotes let strings span multiple rows and contain quotes -val html = """
-

Press belo', Joe

- | -
""" +val sSquared = s. map(sq) + +sSquared.filter(_ < 10) + +sSquared.reduce (_+_) + +// The filter function takes a predicate (a function from A -> Boolean) and +// selects all elements which satisfy the predicate +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)) + + +// Scala a foreach method defined on certain collections that takes a type +// returning Unit (a void method) +aListOfNumbers foreach (x => println(x)) +aListOfNumbers foreach println + +// 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 + +/* 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. */ + + +################################################# +## 8. Implicits +################################################# +Coming soon! -// Application structure and organization +################################################# +## 9. Misc +################################################# // Importing things import scala.collection.immutable.List -- cgit v1.2.3 From 761f150b4bb0374e71aa16a2323a96a89603aaf7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:38:48 -0700 Subject: Clean up of section 1 --- scala.html.markdown | 73 +++++++++++++++++++++++++++++++---------------------- 1 file changed, 43 insertions(+), 30 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index a55e1f0e..a0983bdb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -32,23 +32,36 @@ Scala - the scalable language ## 1. Basics ################################################# +// Single line comments start with two forward slashes + +/* + Multi line comments, as you can already see from above, look like this. +*/ + // Printing, and forcing a new line on the next print println("Hello world!") +println(10) + // Printing, without forcing a new line on next print print("Hello world") -// Declaring values is done using either var or val +// Declaring values is done using either var or val. // val declarations are immutable, whereas var's are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -var x = 10 -x = 20 // x is now 20 +var y = 10 +y = 20 // y is now 20 -// Single line comments start with two forward slashes /* -Multi line comments look like this. + Scala is a statically typed language, yet note that in the above declarations, we did not specify + a type. This is due to a language feature called type inference. In most cases, Scala compiler can + guess what the type of a variable is, so you don't have to type it every time. We can explicitly + declare the type of a variable like so: */ +val z: Int = 10 +val a: Double = 1.0 +val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10 // Boolean values true @@ -65,9 +78,11 @@ true == false // false 2 - 1 // 1 5 * 3 // 15 6 / 2 // 3 +6 / 4 // 1 +6.0 / 4 // 1.5 -// Evaluating a command in the REPL gives you the type and value of the result +// Evaluating an expression in the REPL gives you the type and value of the result 1 + 7 @@ -79,48 +94,46 @@ true == false // false This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 - 1+7 will give you the same result + Note that "res29" is a sequentially generated variable name to store the results of the + expressions you typed, your output may differ. */ - -// Strings - -"Scala strings are surrounded by double quotes" // +"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 -"They also have some extra Scala methods.".reverse -// Seealso: scala.collection.immutable.StringOps +// Strings have the usual Java methods defined on them +"hello world".length +"ABCDEF".substring(2, 6) +"ABCDEF".replace("C", "3") -println("ABCDEF".length) -println("ABCDEF".substring(2, 6)) -println("ABCDEF".replace("C", "3")) +// They also have some extra Scala methods. See also: scala.collection.immutable.StringOps +"hello world".take(5) -// String interpolation +// String interpolation: notice the prefix "s" val n = 45 -println(s"We have $n apples") // => "We have 45 apples" +s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -println(s"My second daughter is ${a(0) - a(2)} years old.") // => "My second daughter is 5 years old." -println(s"We have double the amount of ${n / 2.0} in apples.") // => "We have double the amount of 22.5 in apples." -println(s"Power of 2: ${math.pow(2, 2)}") // => "Power of 2: 4" +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" -// Formatting with interpolated strings (note the prefixed f) -println(f"Power of 5: ${math.pow(5, 2)}%1.0f") // "Power of 5: 25" -println(f"Square root of 122: ${math.sqrt(122)}%1.4f") // "Square root of 122" +// Formatting with interpolated strings with the prefix "f" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122" -// Ignoring special characters. -println(raw"New line feed: \n. Carriage return: \r.") // => "New line feed: \n. Carriage return: \r." +// Raw strings, ignoring special characters. +raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -// Some characters need to be 'escaped', e.g. a double quote inside a string: -val a = "They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" +// Some characters need to be "escaped", e.g. a double quote inside a string: +"They stood outside the \"Rose and Crown\"" // => "They stood outside the "Rose and Crown"" // Triple double-quotes let strings span multiple rows and contain quotes val html = """

Press belo', Joe

- | +
""" -- cgit v1.2.3 From 45bc0f19a0e52d5ccc58db555cb3823c1a00e973 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:46:26 -0700 Subject: Minor fix --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index a0983bdb..6311dba4 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -122,7 +122,7 @@ s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "f" f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" -f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122" +f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. raw"New line feed: \n. Carriage return: \r." // => "New line feed: \n. Carriage return: \r." -- cgit v1.2.3 From e784f52d33475b0cba059a0c07ad01b0e63578a9 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Mon, 10 Nov 2014 19:58:14 -0700 Subject: Minor consistency edit --- scala.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 6311dba4..c8932c86 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -104,11 +104,12 @@ true == false // false // Strings have the usual Java methods defined on them "hello world".length -"ABCDEF".substring(2, 6) -"ABCDEF".replace("C", "3") +"hello world".substring(2, 6) +"hello world".replace("C", "3") // They also have some extra Scala methods. See also: scala.collection.immutable.StringOps "hello world".take(5) +"hello world".drop(5) // String interpolation: notice the prefix "s" val n = 45 -- cgit v1.2.3 From 29bc9a14495a433536a5aaeb1278e56708a81bb7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Wed, 12 Nov 2014 00:36:19 -0800 Subject: Use the right comment style for Scala... oops --- scala.html.markdown | 54 ++++++++++++++++++++++++++--------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 6964b9a0..dc039f0c 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -28,9 +28,9 @@ Scala - the scalable language */ -################################################# -## 1. Basics -################################################# +///////////////////////////////////////////////// +// 1. Basics +///////////////////////////////////////////////// // Single line comments start with two forward slashes @@ -138,9 +138,9 @@ val html = """
""" -################################################# -## 2. Functions -################################################# +///////////////////////////////////////////////// +// 2. Functions +///////////////////////////////////////////////// // The next line gives you a function that takes an Int and returns it squared (x:Int) => x * x @@ -165,9 +165,9 @@ sq(10) // Gives you this: res33: Int = 100. val add10: Int => Int = _ + 10 -################################################# -## 3. Flow Control -################################################# +///////////////////////////////////////////////// +// 3. Flow Control +///////////////////////////////////////////////// 1 to 5 val r = 1 to 5 @@ -220,9 +220,9 @@ println(if (x == 10) "yeah" else "nope") val text = if (x == 10) "yeah" else "nope" -################################################# -## 4. Data Structures -################################################# +///////////////////////////////////////////////// +// 4. Data Structures +///////////////////////////////////////////////// val a = Array(1, 2, 3, 5, 8, 13) a(0) @@ -271,9 +271,9 @@ d._1 d._2 -################################################# -## 5. Object Oriented Programming -################################################# +///////////////////////////////////////////////// +// 5. Object Oriented Programming +///////////////////////////////////////////////// /* Aside: Everything we've done so far in this tutorial has been simple @@ -317,9 +317,9 @@ Person("George", "1234") == Person("Kate", "1236") // Objects and traits coming soon! -################################################# -## 6. Pattern Matching -################################################# +///////////////////////////////////////////////// +// 6. Pattern Matching +///////////////////////////////////////////////// val me = Person("George", "1234") @@ -358,9 +358,9 @@ matcher("52917") // => "No match on '52917'" matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" -################################################# -## 7. Functional Programming -################################################# +///////////////////////////////////////////////// +// 7. Functional Programming +///////////////////////////////////////////////// // Scala allows methods and functions to return, or take as parameters, other // functions or methods. @@ -419,16 +419,16 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared a for-comprehension defines a relationship between two sets of data. */ -################################################# -## 8. Implicits -################################################# +///////////////////////////////////////////////// +// 8. Implicits +///////////////////////////////////////////////// Coming soon! -################################################# -## 9. Misc -################################################# +///////////////////////////////////////////////// +// 9. Misc +///////////////////////////////////////////////// // Importing things import scala.collection.immutable.List -- cgit v1.2.3 From 651e1e90d2da18ee0dd225ef78631c90d519af9d Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Fri, 14 Nov 2014 15:01:16 -0800 Subject: Some work on the Scala page --- scala.html.markdown | 152 ++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 118 insertions(+), 34 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index dc039f0c..529347be 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -54,14 +54,17 @@ var y = 10 y = 20 // y is now 20 /* - Scala is a statically typed language, yet note that in the above declarations, we did not specify - a type. This is due to a language feature called type inference. In most cases, Scala compiler can - guess what the type of a variable is, so you don't have to type it every time. We can explicitly - declare the type of a variable like so: + Scala is a statically typed language, yet note that in the above declarations, + we did not specify a type. This is due to a language feature called type + inference. In most cases, Scala compiler can guess what the type of a variable + is, so you don't have to type it every time. We can explicitly declare the + type of a variable like so: */ val z: Int = 10 val a: Double = 1.0 -val b: Double = 10 // Notice automatic conversion from Int to Double, result is 10.0, not 10 + +// Notice automatic conversion from Int to Double, result is 10.0, not 10 +val b: Double = 10 // Boolean values true @@ -94,8 +97,8 @@ true == false // false This means the result of evaluating 1 + 7 is an object of type Int with a value of 8 - Note that "res29" is a sequentially generated variable name to store the results of the - expressions you typed, your output may differ. + Note that "res29" is a sequentially generated variable name to store the + results of the expressions you typed, your output may differ. */ "Scala strings are surrounded by double quotes" @@ -142,27 +145,69 @@ val html = """
// 2. Functions ///////////////////////////////////////////////// -// The next line gives you a function that takes an Int and returns it squared -(x:Int) => x * x +// Functions are defined like so: +// +// def functionName(args...): ReturnType = { body... } +// +// If you come from more traditional languages, notice the omission of the +// return keyword. In Scala, the last expression in the function block is the +// return value. +def sumOfSquares(x: Int, y: Int): Int = { + val x2 = x * x + val y2 = y * y + x2 + y2 +} -// You can assign this function to an identifier, like this: -val sq = (x:Int) => x * x +// The { } can be omitted if the function body is a single expression: +def sumOfSquaresShort(x: Int, y: Int): Int = x * x + y * y -/* The above says this +// Syntax for calling functions is familiar: +sumOfSquares(3, 4) // => 25 - sq: Int => Int = +// In most cases (with recursive functions the most notable exception), function +// return type can be omitted, and the same type inference we saw with variables +// will work with function return values: +def sq(x: Int) = x * x // Compiler can guess return type is Int - Which means that this time we gave an explicit name to the value - sq is a - function that take an Int and returns Int. +// Functions can have default parameters: +def addWithDefault(x: Int, y: Int = 5) = x + y +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 - sq can be executed as follows: -*/ -sq(10) // Gives you this: res33: Int = 100. +// Anonymous functions look like this: +(x:Int) => x * x -// The colon explicitly defines the type of a value, in this case a function -// taking an Int and returning an Int. -val add10: Int => Int = _ + 10 +// Unlike defs, even the input type of anonymous functions can be omitted if the +// context makes it clear. Notice the type "Int => Int" which means a function +// that takes Int and returns Int. +val sq: Int => Int = x => x * x + +// Anonymous functions can be called as usual: +sq(10) // => 100 + +// If your anonymous function has one or two arguments, and each argument is +// used only once, Scala gives you an even shorter way to define them. These +// anonymous functions turn out to be extremely common, as will be obvious in +// the data structure section. +val addOne: Int => Int = _ + 1 +val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) + +addOne(5) // => 6 +weirdSum(2, 4) // => 16 + + +// The return keyword exists in Scala, but it only returns from the inner-most +// def that surrounds it. It has no effect on anonymous functions. For example: +def foo(x: Int) = { + val anonFunc: Int => Int = { z => + if (z > 5) + return z // This line makes z the return value of foo! + else + z + 2 // This line is the return value of anonFunc + } + anonFunc(x) // This line is the return value of foo +} ///////////////////////////////////////////////// @@ -187,7 +232,7 @@ while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why 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 + // fast, faster that Java loops, but using the combinators and // comprehensions above is easier to understand and parallelize // A do while loop @@ -290,13 +335,24 @@ d._2 And now we will explain what these are. */ +// classes are similar to classes in other languages. Constructor arguments are +// declared after the class name, and initialization is done in the class body. class Dog(br: String) { + // Constructor code here var breed: String = br - //A method called bark, returning a String - def bark: String = { - // the body of the method - "Woof, woof!" - } + + // Define a method called bark, returning a String + def bark = "Woof, woof!" + + // Values and methods are assumed public. "protected" and "private" keywords + // are also available. + private def sleep(hours: Int) = + println(s"I'm sleeping for $hours hours") + + // Abstract methods are simply methods with no body. If we uncomment the next + // line, class Dog would need to be declared abstract + // abstract class Dog(...) { ... } + // def chaseAfter(what: String): String } val mydog = new Dog("greyhound") @@ -304,17 +360,45 @@ println(mydog.breed) // => "greyhound" println(mydog.bark) // => "Woof, woof!" -// Classes can contain nearly any other construct, including other classes, -// functions, methods, objects, case classes, traits etc. +// The "object" keyword creates a type AND a singleton instance of it. It is +// common for Scala classes to have a "companion object", where the per-instance +// behavior is captured in the classes themselves, but behavior related to all +// instance of that class go in objects. The difference is similar to class +// methods vs static methods in other languages. Note that objects and classes +// can have the same name. +object Dog { + def allKnownBreeds = List("pitbull", "shepherd", "retriever") + def createDog(breed: String) = new Dog(breed) +} -// Case classes -case class Person(name:String, phoneNumber:String) +// Case classes are classes that have extra functionality built in. A common +// question for Scala beginners is when to use classes and when to use case +// classes. The line is quite fuzzy, but in general, classes tend to focus on +// encapsulation, polymorphism, and behavior. The values in these classes tend +// to be private, and only methods are exposed. The primary purpose of case +// classes is to hold immutable data. They often have few methods, and the +// methods rarely have side-effects. +case class Person(name: String, phoneNumber: String) + +// Create a new instance. Note cases classes don't need "new" +val george = Person("George", "1234") +val kate = Person("Kate", "4567") + +// With case classes, you get a few perks for free, like getters: +george.phoneNumber // => "1234" + +// Per field equality (no need to override .equals) +Person("George", "1234") == Person("Kate", "1236") // => false + +// Easy way to copy +// otherGeorge == Person("george", "9876") +val otherGeorge = george.copy(phoneNumber = "9876") -Person("George", "1234") == Person("Kate", "1236") +// And many others. Case classes also get pattern matching for free, see below. -// Objects and traits coming soon! +// Traits coming soon! ///////////////////////////////////////////////// @@ -423,7 +507,7 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared // 8. Implicits ///////////////////////////////////////////////// -Coming soon! +// Coming soon! ///////////////////////////////////////////////// -- cgit v1.2.3 From fa2a8209062a3005744a17f3d0912981b43f8942 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 27 Nov 2014 00:38:54 -0700 Subject: Implicits --- scala.html.markdown | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 54 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 529347be..f481f04f 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -507,7 +507,60 @@ for { n <- s; nSquared = n * n if nSquared < 10} yield nSquared // 8. Implicits ///////////////////////////////////////////////// -// Coming soon! +/* WARNING WARNING: Implicits are a set of powerful features of Scala, and + * therefore it is easy to abuse them. Beginners to Scala should resist the + * temptation to use them until they understand not only how they work, but also + * best practices around them. We only include this section in the tutorial + * because they are so commonplace in Scala libraries that it is impossible to + * do anything meaningful without using a library that has implicits. This is + * meant for you to understand and work with implicts, not declare your own. + */ + +// Any value (vals, functions, objects, etc) can be declared to be implicit by +// using the, you guessed it, "implicit" keyword. Note we are using the Dog +// class from section 5 in these examples. +implicit val myImplicitInt = 100 +implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) + +// By itself, implicit keyword doesn't change the behavior of the value, so +// above values can be used as usual. +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" + +// The difference is that these values are now elligible to be used when another +// piece of code "needs" an implicit value. One such situation is implicit +// function arguments: +def sendGreetings(toWhom: String)(implicit howMany: Int) = + s"Hello $toWhom, $howMany blessings to you and yours!" + +// If we supply a value for "howMany", the function behaves as usual +sendGreetings("John")(1000) // => "Hello John, 1000 blessings to you and yours!" + +// But if we omit the implicit parameter, an implicit value of the same type is +// used, in this case, "myImplicitInt": +sendGreetings("Jane") // => "Hello Jane, 100 blessings to you and yours!" + +// Implicit function parameters enable us to simulate type classes in other +// functional languages. It is so often used that it gets its own shorthand. The +// following two lines mean the same thing: +def foo[T](implicit c: C[T]) = ... +def foo[T : C] = ... + + +// Another situation in which the compiler looks for an implicit is if you have +// obj.method(...) +// but "obj" doesn't have "method" as a method. In this case, if there is an +// implicit conversion of type A => B, where A is the type of obj, and B has a +// method called "method", that conversion is applied. So having +// myImplicitFunction above in scope, we can say: +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" + +// Here the String is first converted to Dog using our function above, and then +// the appropriate method is called. This is an extremely powerful feature, but +// again, it is not to be used lightly. In fact, when you defined the implicit +// function above, your compiler should have given you a warning, that you +// shouldn't do this unless you really know what you're doing. ///////////////////////////////////////////////// -- cgit v1.2.3 From 448aee0ed7b68d1ad029d78f3ac157eeba8c3555 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 27 Nov 2014 00:40:32 -0700 Subject: Fix a typo --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index f481f04f..5a478f2a 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -527,7 +527,7 @@ implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) myImplicitInt + 2 // => 102 myImplicitFunction("Pitbull").breed // => "Golden Pitbull" -// The difference is that these values are now elligible to be used when another +// The difference is that these values are now eligible to be used when another // piece of code "needs" an implicit value. One such situation is implicit // function arguments: def sendGreetings(toWhom: String)(implicit howMany: Int) = -- cgit v1.2.3 From 6027c90c90a55702d003f17a72fd82ed7f870be0 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sat, 20 Dec 2014 23:03:25 +0100 Subject: Scala compiler fails to infer the return type when there's an explicit return statement --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..35645922 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -199,7 +199,7 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most // def that surrounds it. It has no effect on anonymous functions. For example: -def foo(x: Int) = { +def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) return z // This line makes z the return value of foo! -- cgit v1.2.3 From 6dca0e7ae41140765cb3b0c1513cfa897294efe5 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sun, 21 Dec 2014 13:08:21 +0100 Subject: Fixed Person class' constructor signature --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 5a478f2a..544abd5b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -476,7 +476,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, phoneNumber:String) +case class Person(name:String, age:Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) -- cgit v1.2.3 From d7672a2bc53dd8b81c4da8c620178cc2458c9238 Mon Sep 17 00:00:00 2001 From: Artur Mkrtchyan Date: Sat, 3 Jan 2015 19:48:53 +0100 Subject: Added warning on return usage --- scala.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 35645922..cfc5a1e9 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -198,7 +198,9 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. It has no effect on anonymous functions. For example: +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. +// It has no effect on anonymous functions. For example: def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) -- cgit v1.2.3 From 8f29b15cda9cbc7ca8fc1f31ed0755245c9fc9c7 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 11 Jan 2015 15:30:12 -0700 Subject: Rewrite the pattern matching section --- scala.html.markdown | 64 ++++++++++++++++++++++++++++++++--------------------- 1 file changed, 39 insertions(+), 25 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 336251ba..3fa4d4b8 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -198,8 +198,8 @@ weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most -// def that surrounds it. -// WARNING: Using return in Scala is error-prone and should be avoided. +// def that surrounds it. +// WARNING: Using return in Scala is error-prone and should be avoided. // It has no effect on anonymous functions. For example: def foo(x: Int): Int = { val anonFunc: Int => Int = { z => @@ -407,41 +407,55 @@ val otherGeorge = george.copy(phoneNumber = "9876") // 6. Pattern Matching ///////////////////////////////////////////////// -val me = Person("George", "1234") +// Pattern matching is a powerful and commonly used feature in Scala. Here's how +// you pattern match a case class. NB: Unlike other languages, Scala cases do +// not have breaks. -me match { case Person(name, number) => { - "We matched someone : " + name + ", phone : " + number }} - -me match { case Person(name, number) => "Match : " + name; case _ => "Hm..." } +def matchPerson(person: Person): String = person match { + // Then you specify the patterns: + case Person("George", number) => "We found George! His number is " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number +} -me match { case Person("George", number) => "Match"; case _ => "Hm..." } +val email = "(.*)@(.*)".r // Define a regex for the next example. -me match { case Person("Kate", number) => "Match"; case _ => "Hm..." } +// Pattern matching might look familiar to the switch statements in the C family +// of languages, but this is much more powerful. In Scala, you can match much +// more: +def matchEverything(obj: Any): String = obj match { + // You can match values: + case "Hello world" => "Got the string Hello world" -me match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match by type: + case x: Double => "Got a Double: " + x -val kate = Person("Kate", "1234") + // You can specify conditions: + case x: Int if x > 10000 => "Got a pretty big number!" -kate match { case Person("Kate", _) => "Girl"; case Person("George", _) => "Boy" } + // You can match case classes as before: + case Person(name, number) => s"Got contact info for $name!" + // You can match regular expressions: + case email(name, domain) => s"Got email address $name@$domain" + // You can match tuples: + case (a: Int, b: Double, c: String) => s"Got a tuple: $a, $b, $c" -// Regular expressions -val email = "(.*)@(.*)".r // Invoking r on String makes it a Regex -val serialKey = """(\d{5})-(\d{5})-(\d{5})-(\d{5})""".r // Using verbatim (multiline) syntax + // You can match data structures: + case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" -val matcher = (value: String) => { - println(value match { - case email(name, domain) => s"It was an email: $name" - case serialKey(p1, p2, p3, p4) => s"Serial key: $p1, $p2, $p3, $p4" - case _ => s"No match on '$value'" // default if no match found - }) + // You can nest patterns: + case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" } -matcher("mrbean@pyahoo.com") // => "It was an email: mrbean" -matcher("nope..") // => "No match on 'nope..'" -matcher("52917") // => "No match on '52917'" -matcher("52752-16432-22178-47917") // => "Serial key: 52752, 16432, 22178, 47917" +// In fact, you can pattern match any object with an "unapply" method. This +// feature is so powerful that Scala lets you define whole functions as +// patterns: +val patternFunc: Person => String = { + case Person("George", number") => s"George's number: $number" + case Person(name, number) => s"Random person's number: $number" +} ///////////////////////////////////////////////// -- cgit v1.2.3 From c053f1559bb357d9e8ced2452096bf3a95cc7ddb Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Sun, 11 Jan 2015 18:11:06 -0700 Subject: Better wording about breaks in cases --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 3fa4d4b8..61c735e3 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -409,7 +409,7 @@ val otherGeorge = george.copy(phoneNumber = "9876") // Pattern matching is a powerful and commonly used feature in Scala. Here's how // you pattern match a case class. NB: Unlike other languages, Scala cases do -// not have breaks. +// not need breaks, fall-through does not happen. def matchPerson(person: Person): String = person match { // Then you specify the patterns: -- cgit v1.2.3 From 73025e65c3f0729ae68c8967b6382de2fedbb13f Mon Sep 17 00:00:00 2001 From: Ikrom Date: Thu, 29 Jan 2015 09:03:36 +0500 Subject: Update scala.html.markdown Removed typo (unnecessary double quote in patternFunc) --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 61c735e3..ed1ddabb 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -453,7 +453,7 @@ def matchEverything(obj: Any): String = obj match { // feature is so powerful that Scala lets you define whole functions as // patterns: val patternFunc: Person => String = { - case Person("George", number") => s"George's number: $number" + case Person("George", number) => s"George's number: $number" case Person(name, number) => s"Random person's number: $number" } -- cgit v1.2.3 From 4adbf231c805afdf68fed3a5e2aba9c90fd4c0c1 Mon Sep 17 00:00:00 2001 From: yejinchang Date: Thu, 16 Apr 2015 17:53:40 +0800 Subject: make corrections --- scala.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index ed1ddabb..e6638121 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -186,7 +186,7 @@ val sq: Int => Int = x => x * x // Anonymous functions can be called as usual: sq(10) // => 100 -// If your anonymous function has one or two arguments, and each argument is +// If each argument in your anonymous function is // used only once, Scala gives you an even shorter way to define them. These // anonymous functions turn out to be extremely common, as will be obvious in // the data structure section. @@ -465,6 +465,7 @@ val patternFunc: Person => String = { // Scala allows methods and functions to return, or take as parameters, other // functions or methods. +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: -- cgit v1.2.3 From 496b11f8ce33f38fc1e29c23ee8c4261a811b967 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:47:02 +0700 Subject: scala: consistent style, language correction --- scala.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index e6638121..12441af9 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -16,15 +16,16 @@ Scala - the scalable language 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: + 2) Unzip/untar to your favourite location and put the bin subdir in your `PATH` environment variable + 3) Start a Scala REPL by running `scala`. You should see the prompt: scala> - This is the so called REPL (Read-Eval-Print Loop). You may type any valid - Scala expression into it, and the result will be printed. We will explain what - Scala files look like further into this tutorial, but for now, let's start - with some basics. + This is the so called REPL (Read-Eval-Print Loop). You may type any Scala + expression, and the result will be printed. We will explain what Scala files + look like further into this tutorial, but for now, let's start with some + basics. + */ -- cgit v1.2.3 From 9ddf69a14da14c0d29abb5a18b4d2dfd5a39c7b2 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:48:28 +0700 Subject: scala: language correction --- scala.html.markdown | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 12441af9..4121dc9b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -5,6 +5,7 @@ contributors: - ["George Petrov", "http://github.com/petrovg"] - ["Dominic Bou-Samra", "http://dbousamra.github.com"] - ["Geoff Liu", "http://geoffliu.me"] + - ["Ha-Duong Nguyen", "http://reference-error.org"] filename: learn.scala --- @@ -33,10 +34,10 @@ Scala - the scalable language // 1. Basics ///////////////////////////////////////////////// -// Single line comments start with two forward slashes +// Single-line comments start with two forward slashes /* - Multi line comments, as you can already see from above, look like this. + Multi-line comments, as you can already see from above, look like this. */ // Printing, and forcing a new line on the next print -- cgit v1.2.3 From 8c06438ec9aec991b78bbd49d2343dc820da7669 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:49:15 +0700 Subject: scala: correct format --- scala.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 4121dc9b..03d80043 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -48,7 +48,7 @@ println(10) print("Hello world") // Declaring values is done using either var or val. -// val declarations are immutable, whereas var's are mutable. Immutability is +// val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 x = 20 // error: reassignment to val -- cgit v1.2.3 From 5b683b34ddb313b8981f360c4a6b54cfbc3af396 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:49:54 +0700 Subject: scala: easier-to-look comment --- scala.html.markdown | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 03d80043..0bd1a56d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -51,9 +51,9 @@ print("Hello world") // val declarations are immutable, whereas vars are mutable. Immutability is // a good thing. val x = 10 // x is now 10 -x = 20 // error: reassignment to val +x = 20 // error: reassignment to val var y = 10 -y = 20 // y is now 20 +y = 20 // y is now 20 /* Scala is a statically typed language, yet note that in the above declarations, @@ -73,17 +73,17 @@ true false // Boolean operations -!true // false -!false // true +!true // false +!false // true true == false // false -10 > 5 // true +10 > 5 // true // Math is as per usual -1 + 1 // 2 -2 - 1 // 1 -5 * 3 // 15 -6 / 2 // 3 -6 / 4 // 1 +1 + 1 // 2 +2 - 1 // 1 +5 * 3 // 15 +6 / 2 // 3 +6 / 4 // 1 6.0 / 4 // 1.5 -- cgit v1.2.3 From dbdde5134b4c5777467a81c8fdf2128cb44edacc Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:50:32 +0700 Subject: scala: clearer comments --- scala.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 0bd1a56d..8d93169b 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -122,12 +122,12 @@ s"We have $n apples" // => "We have 45 apples" // Expressions inside interpolated strings are also possible val a = Array(11, 9, 6) -s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." +s"My second daughter is ${a(0) - a(2)} years old." // => "My second daughter is 5 years old." s"We have double the amount of ${n / 2.0} in apples." // => "We have double the amount of 22.5 in apples." -s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" +s"Power of 2: ${math.pow(2, 2)}" // => "Power of 2: 4" // Formatting with interpolated strings with the prefix "f" -f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" +f"Power of 5: ${math.pow(5, 2)}%1.0f" // "Power of 5: 25" f"Square root of 122: ${math.sqrt(122)}%1.4f" // "Square root of 122: 11.0454" // Raw strings, ignoring special characters. -- cgit v1.2.3 From efb338608b3b6e5af3652e71aa7fb85bdf5917b9 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:55:38 +0700 Subject: scala: consistent code format --- scala.html.markdown | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 8d93169b..62af31b6 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -173,8 +173,8 @@ def sq(x: Int) = x * x // Compiler can guess return type is Int // Functions can have default parameters: def addWithDefault(x: Int, y: Int = 5) = x + y -addWithDefault(1, 2) // => 3 -addWithDefault(1) // => 6 +addWithDefault(1, 2) // => 3 +addWithDefault(1) // => 6 // Anonymous functions look like this: @@ -195,8 +195,8 @@ sq(10) // => 100 val addOne: Int => Int = _ + 1 val weirdSum: (Int, Int) => Int = (_ * 2 + _ * 3) -addOne(5) // => 6 -weirdSum(2, 4) // => 16 +addOne(5) // => 6 +weirdSum(2, 4) // => 16 // The return keyword exists in Scala, but it only returns from the inner-most @@ -206,9 +206,9 @@ weirdSum(2, 4) // => 16 def foo(x: Int): Int = { val anonFunc: Int => Int = { z => if (z > 5) - return z // This line makes z the return value of foo! + return z // This line makes z the return value of foo! else - z + 2 // This line is the return value of anonFunc + z + 2 // This line is the return value of anonFunc } anonFunc(x) // This line is the return value of foo } @@ -361,7 +361,7 @@ class Dog(br: String) { val mydog = new Dog("greyhound") println(mydog.breed) // => "greyhound" -println(mydog.bark) // => "Woof, woof!" +println(mydog.bark) // => "Woof, woof!" // The "object" keyword creates a type AND a singleton instance of it. It is @@ -543,8 +543,8 @@ implicit def myImplicitFunction(breed: String) = new Dog("Golden " + breed) // By itself, implicit keyword doesn't change the behavior of the value, so // above values can be used as usual. -myImplicitInt + 2 // => 102 -myImplicitFunction("Pitbull").breed // => "Golden Pitbull" +myImplicitInt + 2 // => 102 +myImplicitFunction("Pitbull").breed // => "Golden Pitbull" // The difference is that these values are now eligible to be used when another // piece of code "needs" an implicit value. One such situation is implicit @@ -572,8 +572,8 @@ def foo[T : C] = ... // implicit conversion of type A => B, where A is the type of obj, and B has a // method called "method", that conversion is applied. So having // myImplicitFunction above in scope, we can say: -"Retriever".breed // => "Golden Retriever" -"Sheperd".bark // => "Woof, woof!" +"Retriever".breed // => "Golden Retriever" +"Sheperd".bark // => "Woof, woof!" // Here the String is first converted to Dog using our function above, and then // the appropriate method is called. This is an extremely powerful feature, but -- cgit v1.2.3 From 7c02089687eaee9c1fe9b1db3ab0674153077f56 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:55:59 +0700 Subject: scala: consistent code format --- scala.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 62af31b6..35042ebe 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -220,19 +220,19 @@ def foo(x: Int): Int = { 1 to 5 val r = 1 to 5 -r.foreach( println ) +r.foreach(println) r foreach println // 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 -(5 to 1 by -1) foreach ( println ) +(5 to 1 by -1) foreach (println) // A while loops var i = 0 -while (i < 10) { println("i " + i); i+=1 } +while (i < 10) { println("i " + i); i += 1 } -while (i < 10) { println("i " + i); i+=1 } // Yes, again. What happened? Why? +while (i < 10) { println("i " + i); i += 1 } // Yes, again. What happened? Why? 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 @@ -241,19 +241,19 @@ i // Show the value of i. Note that while is a loop in the classical sense - // A do while loop do { - println("x is still less than 10"); + println("x is still less than 10") x += 1 } while (x < 10) // 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 = { +def showNumbersInRange(a:Int, b:Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) } -showNumbersInRange(1,14) +showNumbersInRange(1, 14) // Conditionals @@ -307,13 +307,13 @@ s(1) (a, 2, "three") // Why have this? -val divideInts = (x:Int, y:Int) => (x / y, x % y) +val divideInts = (x: Int, y: Int) => (x / y, x % y) -divideInts(10,3) // The function divideInts gives you the result and the remainder +divideInts(10, 3) // The function divideInts gives you the result and the remainder // To access the elements of a tuple, use _._n where n is the 1-based index of // the element -val d = divideInts(10,3) +val d = divideInts(10, 3) d._1 @@ -416,8 +416,8 @@ val otherGeorge = george.copy(phoneNumber = "9876") def matchPerson(person: Person): String = person match { // Then you specify the patterns: case Person("George", number) => "We found George! His number is " + number - case Person("Kate", number) => "We found Kate! Her number is " + number - case Person(name, number) => "We matched someone : " + name + ", phone : " + number + case Person("Kate", number) => "We found Kate! Her number is " + number + case Person(name, number) => "We matched someone : " + name + ", phone : " + number } val email = "(.*)@(.*)".r // Define a regex for the next example. @@ -448,7 +448,7 @@ def matchEverything(obj: Any): String = obj match { case List(1, b, c) => s"Got a list with three elements and starts with 1: 1, $b, $c" // You can nest patterns: - case List(List((1, 2,"YAY"))) => "Got a list of list of tuple" + case List(List((1, 2, "YAY"))) => "Got a list of list of tuple" } // In fact, you can pattern match any object with an "unapply" method. This @@ -495,7 +495,7 @@ sSquared.reduce (_+_) // The filter function takes a predicate (a function from A -> Boolean) and // selects all elements which satisfy the predicate List(1, 2, 3) filter (_ > 2) // List(3) -case class Person(name:String, age:Int) +case class Person(name: String, age: Int) List( Person(name = "Dom", age = 23), Person(name = "Bob", age = 30) @@ -596,7 +596,7 @@ import scala.collection.immutable._ import scala.collection.immutable.{List, Map} // Rename an import using '=>' -import scala.collection.immutable.{ List => ImmutableList } +import scala.collection.immutable.{List => ImmutableList} // Import all classes, except some. The following excludes Map and Set: import scala.collection.immutable.{Map => _, Set => _, _} -- cgit v1.2.3 From 513235c4754f87e64e5d564bb53ec643ce9333df Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:56:11 +0700 Subject: scala: clearer further resources (itemized) --- scala.html.markdown | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 35042ebe..10db5f78 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -631,13 +631,8 @@ writer.close() ## Further resources -[Scala for the impatient](http://horstmann.com/scala/) - -[Twitter Scala school](http://twitter.github.io/scala_school/) - -[The scala documentation](http://docs.scala-lang.org/) - -[Try Scala in your browser](http://scalatutorials.com/tour/) - -Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) - +* [Scala for the impatient](http://horstmann.com/scala/) +* [Twitter Scala school](http://twitter.github.io/scala_school/) +* [The scala documentation](http://docs.scala-lang.org/) +* [Try Scala in your browser](http://scalatutorials.com/tour/) +* Join the [Scala user group](https://groups.google.com/forum/#!forum/scala-user) -- cgit v1.2.3 From d61ad107759c99de3dd32dc848086c16dbb14f15 Mon Sep 17 00:00:00 2001 From: "Ha-Duong, NGUYEN" Date: Mon, 3 Aug 2015 15:58:36 +0700 Subject: scala: consistent code format --- scala.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'scala.html.markdown') diff --git a/scala.html.markdown b/scala.html.markdown index 10db5f78..c482752d 100644 --- a/scala.html.markdown +++ b/scala.html.markdown @@ -178,7 +178,7 @@ addWithDefault(1) // => 6 // Anonymous functions look like this: -(x:Int) => x * x +(x: Int) => x * x // Unlike defs, even the input type of anonymous functions can be omitted if the // context makes it clear. Notice the type "Int => Int" which means a function @@ -248,7 +248,7 @@ do { // 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 = { +def showNumbersInRange(a: Int, b: Int): Unit = { print(a) if (a < b) showNumbersInRange(a + 1, b) -- cgit v1.2.3