The document discusses Scala programming concepts including object-oriented programming, functional programming, collections, pattern matching, and more. It provides code examples of defining objects and classes, functions, for expressions, match expressions, case classes, traits, generics, and collections like List and Map.
10. // String Unit
// println puts
val puts: String => Unit = println
puts(”hey!”)
def fun1(x: Int): Int = {
def fun2(y: Int): Int = x * y
fun2(5) //
}
val fun3 = (z: Int) => fun1(z + 2)
fun3(3) // 25
11. def matcher(l: List[Int]): Int = l match {
case List(1, 2) => 1
case List(2, 3) => 2
case _ => 0
}
val l = for {
i <- List(1, 2, 3, 4)
if (i > 1)
} yield i // List(2, 3, 4)
l = [1, 2, 3, 4].find_all {|i| i > 1}
l = [i for i in (1, 2, 3, 4) if (i > 1)]
16. ‣ object
class
object
final class Application$cls
private var Application$instance = null
final def Application = {
if (Application$instance == null)
Application$instance = new Application$cls
return Application$instance
}
21. val str: String = ”hey”
val i = 123 //
val f = 5.0
val longstr = ”””test”test”””
val tuple = (1, 2, 3)
val xml =
<property>
<name>prop</name>
<value>{longstr}{tuple(0)}</value>
</property>
22.
23. Any
AnyVal AnyRef
Unit ScalaObject Java
Boolean Char
Byte Short ... ...
Int Long ... ...
Float Double ... ...
Null
Nothing
25. class {
}
class extends {
}
class extends
with ... {
}
private class ... {}
protected class ... {}
sealed class ... {}
abstract class ... {}
final class ... {}
36. trait Named {
private var name_ = quot;quot;
def name = name_
def name_=(v: String) = { name_ = v }
}
class Person(firstName: String,
lastName: String)
extends AnyRef with Named {
name = firstName + quot; quot; + lastName
}
trait SuperMonkeys {
val reina = new Person(quot;Reinaquot;, quot;Miyauchiquot;)
val lina = new Person(quot;Ritsukoquot;, quot;Matsudaquot;)
val mina = new Person(quot;Minakoquot;, quot;Amahisaquot;)
val nana = new Person(quot;Nanakoquot;, quot;Takushiquot;)
}
// extends
class with SuperMonkeys {
}
42. class Card {}
trait Colored {
val color: String
}
case class NumberedCard(color: String,
number: Int)
extends Card with Colored {}
case class WildCard extends Card {}
case class DrawTwo(color: String)
extends Card with Colored {}
case class DrawFour extends Card {}
def putCard = this.discarded match {
case NumberedCard(color, number) => 1
case WildCard(color) => 2
case DrawTwo(color) => 3
case DrawFour(color) => 4
}
44. for (a <- (1, 2, 3, 4)) {
println(a)
}
//
for (a <- (1, 2, 3, 4);
b <- (1, 2, 3, 4)) {
println(a)
println(b)
}
45. var result = List[Int]()
for (i <- List(1, 2, 3, 4)) {
result += (i * i)
}
val result = for (i <- List(1, 2, 3, 4))
yield i * i
46.
47.
48.
49. val (a, b, c) = (1, 2, 3)
var l = List(1, 2, 3) // val
l += 4
println(l) // 1, 2, 3, 4
import scala.collection.mutable._
val l = new ListBuffer[Int]()
l ++= List(1, 2, 3, 4)
l += 5
println(l) // 1, 2, 3, 4, 5