summaryrefslogtreecommitdiffhomepage
path: root/scala.html.markdown
diff options
context:
space:
mode:
Diffstat (limited to 'scala.html.markdown')
-rw-r--r--scala.html.markdown269
1 files changed, 211 insertions, 58 deletions
diff --git a/scala.html.markdown b/scala.html.markdown
index dc039f0c..61c735e3 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,71 @@ val html = """<form id="daform">
// 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 = <function1>
+// 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.
+// 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)
+ 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 +234,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 +337,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,58 +362,100 @@ 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 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"
-// Case classes
+// Per field equality (no need to override .equals)
+Person("George", "1234") == Person("Kate", "1236") // => false
-case class Person(name:String, phoneNumber:String)
+// 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!
/////////////////////////////////////////////////
// 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 need breaks, fall-through does not happen.
-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"
+}
/////////////////////////////////////////////////
@@ -392,7 +492,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)
@@ -423,7 +523,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 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) =
+ 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.
/////////////////////////////////////////////////