SlideShare a Scribd company logo
1 of 75
Download to read offline
Scala
Amir H. Payberah
amir@sics.se
Amirkabir University of Technology
(Tehran Polytechnic)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 1 / 71
Scala
Scala: scalable language
A blend of object-oriented and functional programming.
Runs on the Java Virtual Machine.
Designed by Martin Odersky at EPFL.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 2 / 71
Scala
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 3 / 71
Cathedral vs. Bazaar
Two metaphors for software development
(Eric S. Raymond)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 4 / 71
Cathedral vs. Bazaar
The cathedral
• A near-perfect building that takes a long time to build.
• Once built, it stays unchanged for a long time.
The bazaar
• Adapted and extended each day by the people working in it.
• Open-source software development.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 5 / 71
Cathedral vs. Bazaar
The cathedral
• A near-perfect building that takes a long time to build.
• Once built, it stays unchanged for a long time.
The bazaar
• Adapted and extended each day by the people working in it.
• Open-source software development.
Scala is much more like a bazaar than a cathedral!
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 5 / 71
Functional Programming (FP)
In a restricted sense: programming without mutable variables, as-
signments, loops, and other imperative control structures.
In a wider sense: focusing on the functions.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 6 / 71
Functional Programming (FP)
In a restricted sense: programming without mutable variables, as-
signments, loops, and other imperative control structures.
In a wider sense: focusing on the functions.
Functions can be values that are produced, consumed, and com-
posed.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 6 / 71
FP Languages (1/2)
In a restricted sense: a language that does not have mutable vari-
ables, assignments, or imperative control structures.
In a wider sense: it enables the construction of programs that focus
on functions.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 7 / 71
FP Languages (1/2)
In a restricted sense: a language that does not have mutable vari-
ables, assignments, or imperative control structures.
In a wider sense: it enables the construction of programs that focus
on functions.
Functions are first-class citizens:
• Defined anywhere (including inside other functions).
• Passed as parameters to functions and returned as results.
• Operators to compose functions.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 7 / 71
FP Languages (2/2)
In the restricted sense:
• Pure Lisp, XSLT, XPath, XQuery, Erlang
In the wider sense:
• Lisp, Scheme, Racket, Clojure, SML, Ocaml, Haskell (full language),
Scala, Smalltalk, Ruby
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 8 / 71
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 9 / 71
The “Hello, world!” Program
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 10 / 71
Run It Interactively!
> scala
This is a Scala shell.
Type in expressions to have them evaluated.
Type :help for more information.
scala> object HelloWorld {
| def main(args: Array[String]) {
| println("Hello, world!")
| }
| }
defined module HelloWorld
scala> HelloWorld.main(null)
Hello, world!
scala>:q
>
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 11 / 71
Compile and Execute It!
// Compile it!
> scalac HelloWorld.scala
> scalac -d classes HelloWorld.scala
// Execute it!
> scala HelloWorld
> scala -cp classes HelloWorld
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 12 / 71
Script It!
# script.sh
#!/bin/bash
exec scala $0 $@
!#
object HelloWorld {
def main(args: Array[String]) {
println("Hello, world!")
}
}
HelloWorld.main(null)
# Execute it!
> ./script.sh
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 13 / 71
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 14 / 71
Outline
Scala basics
Functions
Collections
Classes and objects
SBT
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 15 / 71
Outline
Scala basics
Functions
Collections
Classes and objects
SBT
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 15 / 71
Scala Variables
Values: immutable
Variables: mutable
var myVar: Int = 0
val myVal: Int = 1
// Scala figures out the type of variables based on the assigned values
var myVar = 0
val myVal = 1
// If the initial values are not assigned, it cannot figure out the type
var myVar: Int
val myVal: Int
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 16 / 71
Scala Data Types
Boolean: true or false
Byte: 8 bit signed value
Short: 16 bit signed value
Char: 16 bit unsigned Unicode character
Int: 32 bit signed value
Long: 64 bit signed value
Float: 32 bit IEEE 754 single-precision float
Double: 64 bit IEEE 754 double-precision float
String: A sequence of characters
var myInt: Int
var myString: String
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 17 / 71
If ... Else
var x = 30;
if (x == 10) {
println("Value of X is 10");
} else if (x == 20) {
println("Value of X is 20");
} else {
println("This is else statement");
}
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 18 / 71
Loops (1/3)
var a = 10
// do-while
do {
println("Value of a: " + a)
a = a + 1
} while(a < 20)
// while loop execution
while(a < 20) {
println("Value of a: " + a)
a = a + 1
}
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 19 / 71
Loops (2/3)
var a = 0
var b = 0
for (a <- 1 to 3; b <- 1 until 3) {
println("Value of a: " + a + ", b: " + b )
}
Value of a: 1, b: 1
Value of a: 1, b: 2
Value of a: 2, b: 1
Value of a: 2, b: 2
Value of a: 3, b: 1
Value of a: 3, b: 2
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 20 / 71
Loops (3/3)
// loop with collections
val numList = List(1, 2, 3, 4, 5, 6)
for (a <- numList) {
println("Value of a: " + a)
}
// for loop with multiple filters
for (a <- numList if a != 3; if a < 5) {
println("Value of a: " + a)
}
// for loop with a yield
// store return values from a for loop in a variable
var retVal = for(a <- numList if a != 3; if a < 6) yield a
println(retVal)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 21 / 71
Exception Handling
import java.io.FileReader
import java.io.FileNotFoundException
import java.io.IOException
object Test {
def main(args: Array[String]) {
try {
val f = new FileReader("input.txt")
} catch {
case ex: FileNotFoundException => { println("Missing file exception") }
case ex: IOException => { println("IO Exception") }
} finally {
println("Exiting finally...")
}
}
}
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 22 / 71
Outline
Scala basics
Functions
Collections
Classes and objects
SBT
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 23 / 71
Functions - Definition
def functionName([list of parameters]): [return type] = {
function body
return [expr]
}
def addInt(a: Int, b: Int): Int = {
var sum: Int = 0
sum = a + b
sum
}
println("Returned Value: " + addInt(5, 7))
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 24 / 71
Functions - Default Parameter Values
def addInt(a: Int = 5, b: Int = 7): Int = {
var sum: Int = 0
sum = a + b
return sum
}
println("Returned Value :" + addInt())
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 25 / 71
Functions - Variable Arguments
def printStrings(args: String*) = {
var i: Int = 0;
for (arg <- args) {
println("Arg value[" + i + "] = " + arg )
i = i + 1;
}
}
printStrings("SICS", "Scala", "BigData")
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 26 / 71
Functions - Nested Functions
def factorial(i: Int): Int = {
def fact(i: Int, accumulator: Int): Int = {
if (i <= 1)
accumulator
else
fact(i - 1, i * accumulator)
}
fact(i, 1)
}
println(factorial(5))
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 27 / 71
Functions - Anonymous Functions
Lightweight syntax for defining anonymous functions.
var inc = (x: Int) => x + 1
var x = inc(7) - 1
var mul = (x: Int, y: Int) => x * y
println(mul(3, 4))
var userDir = () => { System.getProperty("user.dir") }
println(userDir())
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 28 / 71
Functions - Higher-Order Functions
def apply(f: Int => String, v: Int) = f(v)
def layout[Int](x: Int) = "[" + x.toString() + "]"
println(apply(layout, 10))
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 29 / 71
Functions - Call-by-Value
Call-by-Value: the value of the parameter is determined before it is
passed to the function.
def time() = {
println("Getting time in nano seconds")
System.nanoTime
}
def delayed(t: Long) {
println("In delayed method")
println("Param: " + t)
}
delayed(time())
Getting time in nano seconds
In delayed method
Param: 2532847321861830
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 30 / 71
Functions - Call-by-Name
Call-by-Name: the value of the parameter is not determined until
it is called within the function.
def time() = {
println("Getting time in nano seconds")
System.nanoTime
}
def delayed2(t: => Long) {
println("In delayed method")
println("Param: " + t)
}
delayed2(time())
In delayed method
Getting time in nano seconds
Param: 2532875587194574
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 31 / 71
Functions - Partial Applied
If you do not pass in arguments for all of the parameters.
def adder(m: Int, n: Int, p: Int) = m + n + p
val add2 = adder(2, _: Int, _: Int)
add2(3, 5)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 32 / 71
Outline
Scala basics
Functions
Collections
Classes and objects
SBT
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 33 / 71
Collections
Scala collections can be mutable and immutable collections.
Mutable collections can be updated or extended in place.
Immutable collections never change: additions, removals, or up-
dates operators return a new collection and leave the old collection
unchanged.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 34 / 71
Collections
Arrays
Lists
Sets
Maps
Tuples
Option
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 35 / 71
Collections - Arrays
A fixed-size sequential collection of elements of the same type
// Array definition
val t: Array[String] = new Array[String](3)
val t = new Array[String](3)
// Assign values or get access to individual elements
t(0) = "zero"; t(1) = "one"; t(2) = "two"
// There is one more way of defining an array
val t = Array("zero", "one", "two")
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 36 / 71
Collections - Lists
A sequential collection of elements of the same type
Lists represent a linked list
// List definition
val l1 = List(1, 2, 3)
val l1 = 1 :: 2 :: 3 :: Nil
// Adding an element to the head of a list
val l2 = 0 :: l1
// Adding an element to the tail of a list
val l3 = l1 :+ 4
// Concatenating lists
val t3 = List(4, 5)
val t4 = l1 ::: t3
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 37 / 71
Collections - Sets
A sequential collection of elements of the same type
No duplicates.
// Set definition
val s = Set(1, 2, 3)
// Add a new element to the set
val s2 = s + 0
// Remove an element from the set
val s3 = s2 - 2
// Test the membership
s.contains(2)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 38 / 71
Collections - Maps
A collection of key/value pairs
// Map definition
var m1: Map[Char, Int] = Map()
val m2 = Map(1 -> "Carbon", 2 -> "Hydrogen")
// Finding the element associated to a key in a map
m2(1)
// Adding an association in a map
val m3 = m2 + (3 -> "Oxygen")
// Returns an iterable containing each key (or values) in the map
m2.keys
m2.values
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 39 / 71
Collections - Tuples
A fixed number of items of different types together
// Tuple definition
val t = (1, "hello", Console)
val t = new Tuple3(1, "hello", 20)
// Tuple getters
t._1
t._2
t._3
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 40 / 71
Collections - Option (1/2)
Sometimes you might or might not have a value.
Java typically returns the value null to indicate nothing found.
• You may get a NullPointerException, if you don’t check it.
Scala has a null value in order to communicate with Java.
• You should use it only for this purpose.
Everyplace else, you should use Option.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 41 / 71
Collections - Option (2/2)
// the value of an Option[type] variable is either Some or None.
scala> var s = Some("abc")
scala> var t: Option[String] = None
scala> val numbers = Map(1 -> "one", 2 -> "two")
numbers: scala.collection.immutable.Map[Int, String] = Map((1, one), (2, two))
scala> numbers.get(2)
res0: Option[String] = Some(two)
scala> numbers.get(3)
res1: Option[String] = None
// Check if an Option value is defined (isDefined and isEmpty).
scala> val result = numbers.get(3).isDefined
result: Boolean = false
// Extract the value of an Option.
scala> val result = numbers.get(3).getOrElse("zero")
result: String = zero
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 42 / 71
Functional Combinators
map
foreach
filter
zip
partition
find
drop and dropWhile
flatten
flatMap
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 43 / 71
Functional Combinators - map
Evaluates a function over each element in the list, returning a list
with the same number of elements
scala> val numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)
scala> numbers.map((i: Int) => i * 2)
res0: List[Int] = List(2, 4, 6, 8)
scala> def timesTwo(i: Int): Int = i * 2
timesTwo: (i: Int)Int
scala> numbers.map(timesTwo _)
or
scala> numbers.map(timesTwo)
res1: List[Int] = List(2, 4, 6, 8)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 44 / 71
Functional Combinators - foreach
It is like map but returns nothing
scala> val numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)
scala> val doubled = numbers.foreach((i: Int) => i * 2)
doubled: Unit = ()
scala> numbers.foreach(print)
1234
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 45 / 71
Functional Combinators - filter
Removes any elements where the function you pass in evaluates to
false
scala> val numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)
scala> numbers.filter((i: Int) => i % 2 == 0)
res0: List[Int] = List(2, 4)
scala> def isEven(i: Int): Boolean = i % 2 == 0
isEven: (i: Int)Boolean
scala> numbers.filter(isEven)
res2: List[Int] = List(2, 4)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 46 / 71
Functional Combinators - zip
Aggregates the contents of two lists into a single list of pairs
scala> val numbers = List(1, 2, 3, 4)
numbers: List[Int] = List(1, 2, 3, 4)
scala> val chars = List("a", "b", "c")
chars: List[String] = List(a, b, c)
scala> numbers.zip(chars)
res0: List[(Int, String)] = List((1, a), (2, b), (3, c))
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 47 / 71
Functional Combinators - partition
Splits a list based on where it falls with respect to a predicate func-
tion
scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> numbers.partition(_ % 2 == 0)
res0: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10), List(1, 3, 5, 7, 9))
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 48 / 71
Functional Combinators - find
Returns the first element of a collection that matches a predicate
function
scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> numbers.find(i => i > 5)
res0: Option[Int] = Some(6)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 49 / 71
Functional Combinators - drop and dropWhile
drop drops the first i elements
dropWhile removes the first elements that match a predicate func-
tion
scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
scala> numbers.drop(5)
res0: List[Int] = List(6, 7, 8, 9, 10)
scala> numbers.dropWhile(_ % 3 != 0)
res1: List[Int] = List(3, 4, 5, 6, 7, 8, 9, 10)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 50 / 71
Functional Combinators - flatten
It collapses one level of nested structure
scala> List(List(1, 2), List(3, 4)).flatten
res0: List[Int] = List(1, 2, 3, 4)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 51 / 71
Functional Combinators - flatMap
It takes a function that works on the nested lists and then concate-
nates the results back together
scala> val nestedNumbers = List(List(1, 2), List(3, 4))
nestedNumbers: List[List[Int]] = List(List(1, 2), List(3, 4))
scala> nestedNumbers.flatMap(x => x.map(_ * 2))
res0: List[Int] = List(2, 4, 6, 8)
// Think of it as short-hand for mapping and then flattening:
scala> nestedNumbers.map((x: List[Int]) => x.map(_ * 2)).flatten
res1: List[Int] = List(2, 4, 6, 8)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 52 / 71
Outline
Scala basics
Functions
Collections
Classes and objects
SBT
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 53 / 71
Everything is an Object
Scala is a pure object-oriented language.
Everything is an object, including numbers.
1 + 2 * 3 / x
(1).+(((2).*(3))./(x))
Functions are also objects, so it is possible to pass functions as
arguments, to store them in variables, and to return them from
other functions.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 54 / 71
Classes and Objects
class Calculator {
val brand: String = "HP"
def add(m: Int, n: Int): Int = m + n
}
val calc = new Calculator
calc.add(1, 2)
println(calc.brand)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 55 / 71
Constructors
class Calculator(brand: String) {
// A constructor.
val color: String = if (brand == "TI") {
"blue"
} else if (brand == "HP") {
"black"
} else {
"white"
}
// An instance method.
def add(m: Int, n: Int): Int = m + n
}
val calc = new Calculator("HP")
println(calc.color)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 56 / 71
Inheritance and Overloading Methods
Scala allows the inheritance from just one class only.
class SciCalculator(brand: String) extends Calculator(brand) {
def log(m: Double, base: Double) = math.log(m) / math.log(base)
}
class MoreSciCalculator(brand: String) extends SciCalculator(brand) {
def log(m: Int): Double = log(m, math.exp(1))
}
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 57 / 71
Singleton Objects
A singleton is a class that can have only one instance.
class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc
}
object Test {
def main(args: Array[String]) {
val point = new Point(10, 20)
printPoint
def printPoint {
println ("Point x location : " + point.x);
println ("Point y location : " + point.y);
}
}
}
Test.main(null)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 58 / 71
Abstract Classes
abstract class Shape {
// subclass should define this
def getArea(): Int
}
class Circle(r: Int) extends Shape {
def getArea(): Int = { r * r * 3 }
}
val s = new Shape // error: class Shape is abstract
val c = new Circle(2)
c.getArea
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 59 / 71
Traits
A class can mix in any number of traits.
trait Car {
val brand: String
}
trait Shiny {
val shineRefraction: Int
}
class BMW extends Car with Shiny {
val brand = "BMW"
val shineRefraction = 12
}
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 60 / 71
Generic Types
trait Cache[K, V] {
def get(key: K): V
def put(key: K, value: V)
def delete(key: K)
}
def remove[K](key: K)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 61 / 71
Case Classes and Pattern Matching
Case classes are used to store and match on the contents of a class.
They are designed to be used with pattern matching.
You can construct them without using new.
scala> case class Calculator(brand: String, model: String)
scala> val hp20b = Calculator("hp", "20B")
def calcType(calc: Calculator) = calc match {
case Calculator("hp", "20B") => "financial"
case Calculator("hp", "48G") => "scientific"
case Calculator("hp", "30B") => "business"
case _ => "Calculator of unknown type"
}
scala> calcType(hp20b)
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 62 / 71
Outline
Scala basics
Functions
Collections
Classes and objects
SBT
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 63 / 71
Simple Build Tool (SBT)
An open source build tool for Scala and Java projects.
Similar to Java’s Maven or Ant.
It is written in Scala.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 64 / 71
SBT - Hello World!
$ mkdir hello
$ cd hello
$ cp <path>/HelloWorld.scala .
$ sbt
...
> run
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 65 / 71
Running SBT
Interactive mode
$ sbt
> compile
> run
Batch mode
$ sbt clean run
Continuous build and test: automatically recompile or run tests
whenever you save a source file.
$ sbt
> ~ compile
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 66 / 71
Common Commands
clean: deletes all generated files (in target).
compile: compiles the main sources (in src/main/scala).
test: compiles and runs all tests.
console: starts the Scala interpreter.
run <argument>*: run the main class.
package: creates a jar file containing the files in src/main/resources
and the classes compiled from src/main/scala.
help <command>: displays detailed help for the specified command.
reload: reloads the build definition (build.sbt, project/*.scala,
project/*.sbt files).
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 67 / 71
Create a Simple Project
Create project directory.
Create src/main/scala directory.
Create build.sbt in the project root.
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 68 / 71
build.sbt
A list of Scala expressions, separated by blank lines.
Located in the project’s base directory.
$ cat build.sbt
name := "hello"
version := "1.0"
scalaVersion := "2.10.3"
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 69 / 71
Add Dependencies
Add in build.sbt.
Module ID format:
"groupID" %% "artifact" % "version" % "configuration"
libraryDependencies += "org.apache.spark" %% "spark-core" % "0.9.0-incubating"
// multiple dependencies
libraryDependencies ++= Seq(
"org.apache.spark" %% "spark-core" % "0.9.0-incubating",
"org.apache.spark" %% "spark-streaming" % "0.9.0-incubating"
)
sbt uses the standard Maven2 repository by default, but you can add
more resolvers.
resolvers += "Akka Repository" at "http://repo.akka.io/releases/"
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 70 / 71
Questions?
Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 71 / 71

More Related Content

What's hot

Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
system software
system software system software
system software randhirlpu
 
More on Lex
More on LexMore on Lex
More on LexTech_MX
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scriptsAmeen San
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg MürkPlanet OS
 
EC6612 VLSI Design Lab Manual
EC6612 VLSI Design Lab ManualEC6612 VLSI Design Lab Manual
EC6612 VLSI Design Lab Manualtamil arasan
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional APIJustin Lin
 
Syntactic Salt and Sugar Presentation
Syntactic Salt and Sugar PresentationSyntactic Salt and Sugar Presentation
Syntactic Salt and Sugar Presentationgrepalex
 
Actor based approach in practice for Swift developers
Actor based approach in practice for Swift developersActor based approach in practice for Swift developers
Actor based approach in practice for Swift developersBartosz Polaczyk
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java DevelopersMichael Galpin
 

What's hot (20)

Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Operator overloading
Operator overloading Operator overloading
Operator overloading
 
system software
system software system software
system software
 
More on Lex
More on LexMore on Lex
More on Lex
 
Matlab m files and scripts
Matlab m files and scriptsMatlab m files and scripts
Matlab m files and scripts
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Compile time polymorphism
Compile time polymorphismCompile time polymorphism
Compile time polymorphism
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Advance Scala - Oleg Mürk
Advance Scala - Oleg MürkAdvance Scala - Oleg Mürk
Advance Scala - Oleg Mürk
 
EC6612 VLSI Design Lab Manual
EC6612 VLSI Design Lab ManualEC6612 VLSI Design Lab Manual
EC6612 VLSI Design Lab Manual
 
VLSI lab manual
VLSI lab manualVLSI lab manual
VLSI lab manual
 
LEX & YACC TOOL
LEX & YACC TOOLLEX & YACC TOOL
LEX & YACC TOOL
 
JDK8 Functional API
JDK8 Functional APIJDK8 Functional API
JDK8 Functional API
 
Syntactic Salt and Sugar Presentation
Syntactic Salt and Sugar PresentationSyntactic Salt and Sugar Presentation
Syntactic Salt and Sugar Presentation
 
Actor based approach in practice for Swift developers
Actor based approach in practice for Swift developersActor based approach in practice for Swift developers
Actor based approach in practice for Swift developers
 
Introduction to Scala for Java Developers
Introduction to Scala for Java DevelopersIntroduction to Scala for Java Developers
Introduction to Scala for Java Developers
 
C++ theory
C++ theoryC++ theory
C++ theory
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 

Viewers also liked

P2P Content Distribution Network
P2P Content Distribution NetworkP2P Content Distribution Network
P2P Content Distribution NetworkAmir Payberah
 
Spark Stream and SEEP
Spark Stream and SEEPSpark Stream and SEEP
Spark Stream and SEEPAmir Payberah
 
Linux Module Programming
Linux Module ProgrammingLinux Module Programming
Linux Module ProgrammingAmir Payberah
 
MegaStore and Spanner
MegaStore and SpannerMegaStore and Spanner
MegaStore and SpannerAmir Payberah
 
Introduction to Operating Systems - Part2
Introduction to Operating Systems - Part2Introduction to Operating Systems - Part2
Introduction to Operating Systems - Part2Amir Payberah
 
Process Management - Part2
Process Management - Part2Process Management - Part2
Process Management - Part2Amir Payberah
 
CPU Scheduling - Part2
CPU Scheduling - Part2CPU Scheduling - Part2
CPU Scheduling - Part2Amir Payberah
 
The Stratosphere Big Data Analytics Platform
The Stratosphere Big Data Analytics PlatformThe Stratosphere Big Data Analytics Platform
The Stratosphere Big Data Analytics PlatformAmir Payberah
 
Data Intensive Computing Frameworks
Data Intensive Computing FrameworksData Intensive Computing Frameworks
Data Intensive Computing FrameworksAmir Payberah
 
The Spark Big Data Analytics Platform
The Spark Big Data Analytics PlatformThe Spark Big Data Analytics Platform
The Spark Big Data Analytics PlatformAmir Payberah
 

Viewers also liked (20)

Spark
SparkSpark
Spark
 
P2P Content Distribution Network
P2P Content Distribution NetworkP2P Content Distribution Network
P2P Content Distribution Network
 
Hive and Shark
Hive and SharkHive and Shark
Hive and Shark
 
Spark Stream and SEEP
Spark Stream and SEEPSpark Stream and SEEP
Spark Stream and SEEP
 
MapReduce
MapReduceMapReduce
MapReduce
 
Linux Module Programming
Linux Module ProgrammingLinux Module Programming
Linux Module Programming
 
MegaStore and Spanner
MegaStore and SpannerMegaStore and Spanner
MegaStore and Spanner
 
Introduction to Operating Systems - Part2
Introduction to Operating Systems - Part2Introduction to Operating Systems - Part2
Introduction to Operating Systems - Part2
 
Protection
ProtectionProtection
Protection
 
Security
SecuritySecurity
Security
 
IO Systems
IO SystemsIO Systems
IO Systems
 
Cloud Computing
Cloud ComputingCloud Computing
Cloud Computing
 
Process Management - Part2
Process Management - Part2Process Management - Part2
Process Management - Part2
 
Main Memory - Part2
Main Memory - Part2Main Memory - Part2
Main Memory - Part2
 
Storage
StorageStorage
Storage
 
CPU Scheduling - Part2
CPU Scheduling - Part2CPU Scheduling - Part2
CPU Scheduling - Part2
 
The Stratosphere Big Data Analytics Platform
The Stratosphere Big Data Analytics PlatformThe Stratosphere Big Data Analytics Platform
The Stratosphere Big Data Analytics Platform
 
Data Intensive Computing Frameworks
Data Intensive Computing FrameworksData Intensive Computing Frameworks
Data Intensive Computing Frameworks
 
The Spark Big Data Analytics Platform
The Spark Big Data Analytics PlatformThe Spark Big Data Analytics Platform
The Spark Big Data Analytics Platform
 
Deadlocks
DeadlocksDeadlocks
Deadlocks
 

Similar to Scala

Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On LabSimon Ritter
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8Martin Toshev
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + ScalaShouheng Yi
 
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaJDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaSimon Ritter
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#Rainer Stropek
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streamsjessitron
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 

Similar to Scala (20)

Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
Lambdas Hands On Lab
Lambdas Hands On LabLambdas Hands On Lab
Lambdas Hands On Lab
 
Lambdas and Laughs
Lambdas and LaughsLambdas and Laughs
Lambdas and Laughs
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Seattle useR Group - R + Scala
Seattle useR Group - R + ScalaSeattle useR Group - R + Scala
Seattle useR Group - R + Scala
 
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing JavaJDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
JDK8 Lambdas and Streams: Changing The Way You Think When Developing Java
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Parallel and Async Programming With C#
Parallel and Async Programming With C#Parallel and Async Programming With C#
Parallel and Async Programming With C#
 
Charles Sharp: Java 8 Streams
Charles Sharp: Java 8 StreamsCharles Sharp: Java 8 Streams
Charles Sharp: Java 8 Streams
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 

More from Amir Payberah

File System Implementation - Part2
File System Implementation - Part2File System Implementation - Part2
File System Implementation - Part2Amir Payberah
 
File System Implementation - Part1
File System Implementation - Part1File System Implementation - Part1
File System Implementation - Part1Amir Payberah
 
File System Interface
File System InterfaceFile System Interface
File System InterfaceAmir Payberah
 
Virtual Memory - Part2
Virtual Memory - Part2Virtual Memory - Part2
Virtual Memory - Part2Amir Payberah
 
Virtual Memory - Part1
Virtual Memory - Part1Virtual Memory - Part1
Virtual Memory - Part1Amir Payberah
 
CPU Scheduling - Part1
CPU Scheduling - Part1CPU Scheduling - Part1
CPU Scheduling - Part1Amir Payberah
 
Process Synchronization - Part2
Process Synchronization -  Part2Process Synchronization -  Part2
Process Synchronization - Part2Amir Payberah
 
Process Synchronization - Part1
Process Synchronization -  Part1Process Synchronization -  Part1
Process Synchronization - Part1Amir Payberah
 
Process Management - Part3
Process Management - Part3Process Management - Part3
Process Management - Part3Amir Payberah
 
Process Management - Part1
Process Management - Part1Process Management - Part1
Process Management - Part1Amir Payberah
 
Introduction to Operating Systems - Part3
Introduction to Operating Systems - Part3Introduction to Operating Systems - Part3
Introduction to Operating Systems - Part3Amir Payberah
 
Introduction to Operating Systems - Part1
Introduction to Operating Systems - Part1Introduction to Operating Systems - Part1
Introduction to Operating Systems - Part1Amir Payberah
 

More from Amir Payberah (15)

File System Implementation - Part2
File System Implementation - Part2File System Implementation - Part2
File System Implementation - Part2
 
File System Implementation - Part1
File System Implementation - Part1File System Implementation - Part1
File System Implementation - Part1
 
File System Interface
File System InterfaceFile System Interface
File System Interface
 
Virtual Memory - Part2
Virtual Memory - Part2Virtual Memory - Part2
Virtual Memory - Part2
 
Virtual Memory - Part1
Virtual Memory - Part1Virtual Memory - Part1
Virtual Memory - Part1
 
Main Memory - Part1
Main Memory - Part1Main Memory - Part1
Main Memory - Part1
 
CPU Scheduling - Part1
CPU Scheduling - Part1CPU Scheduling - Part1
CPU Scheduling - Part1
 
Process Synchronization - Part2
Process Synchronization -  Part2Process Synchronization -  Part2
Process Synchronization - Part2
 
Process Synchronization - Part1
Process Synchronization -  Part1Process Synchronization -  Part1
Process Synchronization - Part1
 
Threads
ThreadsThreads
Threads
 
Process Management - Part3
Process Management - Part3Process Management - Part3
Process Management - Part3
 
Process Management - Part1
Process Management - Part1Process Management - Part1
Process Management - Part1
 
Introduction to Operating Systems - Part3
Introduction to Operating Systems - Part3Introduction to Operating Systems - Part3
Introduction to Operating Systems - Part3
 
Introduction to Operating Systems - Part1
Introduction to Operating Systems - Part1Introduction to Operating Systems - Part1
Introduction to Operating Systems - Part1
 
Mesos and YARN
Mesos and YARNMesos and YARN
Mesos and YARN
 

Recently uploaded

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfproinshot.com
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesVictorSzoltysek
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Scala

  • 1. Scala Amir H. Payberah amir@sics.se Amirkabir University of Technology (Tehran Polytechnic) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 1 / 71
  • 2. Scala Scala: scalable language A blend of object-oriented and functional programming. Runs on the Java Virtual Machine. Designed by Martin Odersky at EPFL. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 2 / 71
  • 3. Scala Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 3 / 71
  • 4. Cathedral vs. Bazaar Two metaphors for software development (Eric S. Raymond) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 4 / 71
  • 5. Cathedral vs. Bazaar The cathedral • A near-perfect building that takes a long time to build. • Once built, it stays unchanged for a long time. The bazaar • Adapted and extended each day by the people working in it. • Open-source software development. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 5 / 71
  • 6. Cathedral vs. Bazaar The cathedral • A near-perfect building that takes a long time to build. • Once built, it stays unchanged for a long time. The bazaar • Adapted and extended each day by the people working in it. • Open-source software development. Scala is much more like a bazaar than a cathedral! Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 5 / 71
  • 7. Functional Programming (FP) In a restricted sense: programming without mutable variables, as- signments, loops, and other imperative control structures. In a wider sense: focusing on the functions. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 6 / 71
  • 8. Functional Programming (FP) In a restricted sense: programming without mutable variables, as- signments, loops, and other imperative control structures. In a wider sense: focusing on the functions. Functions can be values that are produced, consumed, and com- posed. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 6 / 71
  • 9. FP Languages (1/2) In a restricted sense: a language that does not have mutable vari- ables, assignments, or imperative control structures. In a wider sense: it enables the construction of programs that focus on functions. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 7 / 71
  • 10. FP Languages (1/2) In a restricted sense: a language that does not have mutable vari- ables, assignments, or imperative control structures. In a wider sense: it enables the construction of programs that focus on functions. Functions are first-class citizens: • Defined anywhere (including inside other functions). • Passed as parameters to functions and returned as results. • Operators to compose functions. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 7 / 71
  • 11. FP Languages (2/2) In the restricted sense: • Pure Lisp, XSLT, XPath, XQuery, Erlang In the wider sense: • Lisp, Scheme, Racket, Clojure, SML, Ocaml, Haskell (full language), Scala, Smalltalk, Ruby Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 8 / 71
  • 12. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 9 / 71
  • 13. The “Hello, world!” Program object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } } Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 10 / 71
  • 14. Run It Interactively! > scala This is a Scala shell. Type in expressions to have them evaluated. Type :help for more information. scala> object HelloWorld { | def main(args: Array[String]) { | println("Hello, world!") | } | } defined module HelloWorld scala> HelloWorld.main(null) Hello, world! scala>:q > Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 11 / 71
  • 15. Compile and Execute It! // Compile it! > scalac HelloWorld.scala > scalac -d classes HelloWorld.scala // Execute it! > scala HelloWorld > scala -cp classes HelloWorld Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 12 / 71
  • 16. Script It! # script.sh #!/bin/bash exec scala $0 $@ !# object HelloWorld { def main(args: Array[String]) { println("Hello, world!") } } HelloWorld.main(null) # Execute it! > ./script.sh Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 13 / 71
  • 17. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 14 / 71
  • 18. Outline Scala basics Functions Collections Classes and objects SBT Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 15 / 71
  • 19. Outline Scala basics Functions Collections Classes and objects SBT Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 15 / 71
  • 20. Scala Variables Values: immutable Variables: mutable var myVar: Int = 0 val myVal: Int = 1 // Scala figures out the type of variables based on the assigned values var myVar = 0 val myVal = 1 // If the initial values are not assigned, it cannot figure out the type var myVar: Int val myVal: Int Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 16 / 71
  • 21. Scala Data Types Boolean: true or false Byte: 8 bit signed value Short: 16 bit signed value Char: 16 bit unsigned Unicode character Int: 32 bit signed value Long: 64 bit signed value Float: 32 bit IEEE 754 single-precision float Double: 64 bit IEEE 754 double-precision float String: A sequence of characters var myInt: Int var myString: String Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 17 / 71
  • 22. If ... Else var x = 30; if (x == 10) { println("Value of X is 10"); } else if (x == 20) { println("Value of X is 20"); } else { println("This is else statement"); } Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 18 / 71
  • 23. Loops (1/3) var a = 10 // do-while do { println("Value of a: " + a) a = a + 1 } while(a < 20) // while loop execution while(a < 20) { println("Value of a: " + a) a = a + 1 } Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 19 / 71
  • 24. Loops (2/3) var a = 0 var b = 0 for (a <- 1 to 3; b <- 1 until 3) { println("Value of a: " + a + ", b: " + b ) } Value of a: 1, b: 1 Value of a: 1, b: 2 Value of a: 2, b: 1 Value of a: 2, b: 2 Value of a: 3, b: 1 Value of a: 3, b: 2 Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 20 / 71
  • 25. Loops (3/3) // loop with collections val numList = List(1, 2, 3, 4, 5, 6) for (a <- numList) { println("Value of a: " + a) } // for loop with multiple filters for (a <- numList if a != 3; if a < 5) { println("Value of a: " + a) } // for loop with a yield // store return values from a for loop in a variable var retVal = for(a <- numList if a != 3; if a < 6) yield a println(retVal) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 21 / 71
  • 26. Exception Handling import java.io.FileReader import java.io.FileNotFoundException import java.io.IOException object Test { def main(args: Array[String]) { try { val f = new FileReader("input.txt") } catch { case ex: FileNotFoundException => { println("Missing file exception") } case ex: IOException => { println("IO Exception") } } finally { println("Exiting finally...") } } } Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 22 / 71
  • 27. Outline Scala basics Functions Collections Classes and objects SBT Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 23 / 71
  • 28. Functions - Definition def functionName([list of parameters]): [return type] = { function body return [expr] } def addInt(a: Int, b: Int): Int = { var sum: Int = 0 sum = a + b sum } println("Returned Value: " + addInt(5, 7)) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 24 / 71
  • 29. Functions - Default Parameter Values def addInt(a: Int = 5, b: Int = 7): Int = { var sum: Int = 0 sum = a + b return sum } println("Returned Value :" + addInt()) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 25 / 71
  • 30. Functions - Variable Arguments def printStrings(args: String*) = { var i: Int = 0; for (arg <- args) { println("Arg value[" + i + "] = " + arg ) i = i + 1; } } printStrings("SICS", "Scala", "BigData") Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 26 / 71
  • 31. Functions - Nested Functions def factorial(i: Int): Int = { def fact(i: Int, accumulator: Int): Int = { if (i <= 1) accumulator else fact(i - 1, i * accumulator) } fact(i, 1) } println(factorial(5)) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 27 / 71
  • 32. Functions - Anonymous Functions Lightweight syntax for defining anonymous functions. var inc = (x: Int) => x + 1 var x = inc(7) - 1 var mul = (x: Int, y: Int) => x * y println(mul(3, 4)) var userDir = () => { System.getProperty("user.dir") } println(userDir()) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 28 / 71
  • 33. Functions - Higher-Order Functions def apply(f: Int => String, v: Int) = f(v) def layout[Int](x: Int) = "[" + x.toString() + "]" println(apply(layout, 10)) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 29 / 71
  • 34. Functions - Call-by-Value Call-by-Value: the value of the parameter is determined before it is passed to the function. def time() = { println("Getting time in nano seconds") System.nanoTime } def delayed(t: Long) { println("In delayed method") println("Param: " + t) } delayed(time()) Getting time in nano seconds In delayed method Param: 2532847321861830 Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 30 / 71
  • 35. Functions - Call-by-Name Call-by-Name: the value of the parameter is not determined until it is called within the function. def time() = { println("Getting time in nano seconds") System.nanoTime } def delayed2(t: => Long) { println("In delayed method") println("Param: " + t) } delayed2(time()) In delayed method Getting time in nano seconds Param: 2532875587194574 Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 31 / 71
  • 36. Functions - Partial Applied If you do not pass in arguments for all of the parameters. def adder(m: Int, n: Int, p: Int) = m + n + p val add2 = adder(2, _: Int, _: Int) add2(3, 5) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 32 / 71
  • 37. Outline Scala basics Functions Collections Classes and objects SBT Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 33 / 71
  • 38. Collections Scala collections can be mutable and immutable collections. Mutable collections can be updated or extended in place. Immutable collections never change: additions, removals, or up- dates operators return a new collection and leave the old collection unchanged. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 34 / 71
  • 39. Collections Arrays Lists Sets Maps Tuples Option Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 35 / 71
  • 40. Collections - Arrays A fixed-size sequential collection of elements of the same type // Array definition val t: Array[String] = new Array[String](3) val t = new Array[String](3) // Assign values or get access to individual elements t(0) = "zero"; t(1) = "one"; t(2) = "two" // There is one more way of defining an array val t = Array("zero", "one", "two") Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 36 / 71
  • 41. Collections - Lists A sequential collection of elements of the same type Lists represent a linked list // List definition val l1 = List(1, 2, 3) val l1 = 1 :: 2 :: 3 :: Nil // Adding an element to the head of a list val l2 = 0 :: l1 // Adding an element to the tail of a list val l3 = l1 :+ 4 // Concatenating lists val t3 = List(4, 5) val t4 = l1 ::: t3 Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 37 / 71
  • 42. Collections - Sets A sequential collection of elements of the same type No duplicates. // Set definition val s = Set(1, 2, 3) // Add a new element to the set val s2 = s + 0 // Remove an element from the set val s3 = s2 - 2 // Test the membership s.contains(2) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 38 / 71
  • 43. Collections - Maps A collection of key/value pairs // Map definition var m1: Map[Char, Int] = Map() val m2 = Map(1 -> "Carbon", 2 -> "Hydrogen") // Finding the element associated to a key in a map m2(1) // Adding an association in a map val m3 = m2 + (3 -> "Oxygen") // Returns an iterable containing each key (or values) in the map m2.keys m2.values Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 39 / 71
  • 44. Collections - Tuples A fixed number of items of different types together // Tuple definition val t = (1, "hello", Console) val t = new Tuple3(1, "hello", 20) // Tuple getters t._1 t._2 t._3 Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 40 / 71
  • 45. Collections - Option (1/2) Sometimes you might or might not have a value. Java typically returns the value null to indicate nothing found. • You may get a NullPointerException, if you don’t check it. Scala has a null value in order to communicate with Java. • You should use it only for this purpose. Everyplace else, you should use Option. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 41 / 71
  • 46. Collections - Option (2/2) // the value of an Option[type] variable is either Some or None. scala> var s = Some("abc") scala> var t: Option[String] = None scala> val numbers = Map(1 -> "one", 2 -> "two") numbers: scala.collection.immutable.Map[Int, String] = Map((1, one), (2, two)) scala> numbers.get(2) res0: Option[String] = Some(two) scala> numbers.get(3) res1: Option[String] = None // Check if an Option value is defined (isDefined and isEmpty). scala> val result = numbers.get(3).isDefined result: Boolean = false // Extract the value of an Option. scala> val result = numbers.get(3).getOrElse("zero") result: String = zero Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 42 / 71
  • 47. Functional Combinators map foreach filter zip partition find drop and dropWhile flatten flatMap Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 43 / 71
  • 48. Functional Combinators - map Evaluates a function over each element in the list, returning a list with the same number of elements scala> val numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4) scala> numbers.map((i: Int) => i * 2) res0: List[Int] = List(2, 4, 6, 8) scala> def timesTwo(i: Int): Int = i * 2 timesTwo: (i: Int)Int scala> numbers.map(timesTwo _) or scala> numbers.map(timesTwo) res1: List[Int] = List(2, 4, 6, 8) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 44 / 71
  • 49. Functional Combinators - foreach It is like map but returns nothing scala> val numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4) scala> val doubled = numbers.foreach((i: Int) => i * 2) doubled: Unit = () scala> numbers.foreach(print) 1234 Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 45 / 71
  • 50. Functional Combinators - filter Removes any elements where the function you pass in evaluates to false scala> val numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4) scala> numbers.filter((i: Int) => i % 2 == 0) res0: List[Int] = List(2, 4) scala> def isEven(i: Int): Boolean = i % 2 == 0 isEven: (i: Int)Boolean scala> numbers.filter(isEven) res2: List[Int] = List(2, 4) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 46 / 71
  • 51. Functional Combinators - zip Aggregates the contents of two lists into a single list of pairs scala> val numbers = List(1, 2, 3, 4) numbers: List[Int] = List(1, 2, 3, 4) scala> val chars = List("a", "b", "c") chars: List[String] = List(a, b, c) scala> numbers.zip(chars) res0: List[(Int, String)] = List((1, a), (2, b), (3, c)) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 47 / 71
  • 52. Functional Combinators - partition Splits a list based on where it falls with respect to a predicate func- tion scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> numbers.partition(_ % 2 == 0) res0: (List[Int], List[Int]) = (List(2, 4, 6, 8, 10), List(1, 3, 5, 7, 9)) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 48 / 71
  • 53. Functional Combinators - find Returns the first element of a collection that matches a predicate function scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> numbers.find(i => i > 5) res0: Option[Int] = Some(6) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 49 / 71
  • 54. Functional Combinators - drop and dropWhile drop drops the first i elements dropWhile removes the first elements that match a predicate func- tion scala> val numbers = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) numbers: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) scala> numbers.drop(5) res0: List[Int] = List(6, 7, 8, 9, 10) scala> numbers.dropWhile(_ % 3 != 0) res1: List[Int] = List(3, 4, 5, 6, 7, 8, 9, 10) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 50 / 71
  • 55. Functional Combinators - flatten It collapses one level of nested structure scala> List(List(1, 2), List(3, 4)).flatten res0: List[Int] = List(1, 2, 3, 4) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 51 / 71
  • 56. Functional Combinators - flatMap It takes a function that works on the nested lists and then concate- nates the results back together scala> val nestedNumbers = List(List(1, 2), List(3, 4)) nestedNumbers: List[List[Int]] = List(List(1, 2), List(3, 4)) scala> nestedNumbers.flatMap(x => x.map(_ * 2)) res0: List[Int] = List(2, 4, 6, 8) // Think of it as short-hand for mapping and then flattening: scala> nestedNumbers.map((x: List[Int]) => x.map(_ * 2)).flatten res1: List[Int] = List(2, 4, 6, 8) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 52 / 71
  • 57. Outline Scala basics Functions Collections Classes and objects SBT Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 53 / 71
  • 58. Everything is an Object Scala is a pure object-oriented language. Everything is an object, including numbers. 1 + 2 * 3 / x (1).+(((2).*(3))./(x)) Functions are also objects, so it is possible to pass functions as arguments, to store them in variables, and to return them from other functions. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 54 / 71
  • 59. Classes and Objects class Calculator { val brand: String = "HP" def add(m: Int, n: Int): Int = m + n } val calc = new Calculator calc.add(1, 2) println(calc.brand) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 55 / 71
  • 60. Constructors class Calculator(brand: String) { // A constructor. val color: String = if (brand == "TI") { "blue" } else if (brand == "HP") { "black" } else { "white" } // An instance method. def add(m: Int, n: Int): Int = m + n } val calc = new Calculator("HP") println(calc.color) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 56 / 71
  • 61. Inheritance and Overloading Methods Scala allows the inheritance from just one class only. class SciCalculator(brand: String) extends Calculator(brand) { def log(m: Double, base: Double) = math.log(m) / math.log(base) } class MoreSciCalculator(brand: String) extends SciCalculator(brand) { def log(m: Int): Double = log(m, math.exp(1)) } Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 57 / 71
  • 62. Singleton Objects A singleton is a class that can have only one instance. class Point(val xc: Int, val yc: Int) { var x: Int = xc var y: Int = yc } object Test { def main(args: Array[String]) { val point = new Point(10, 20) printPoint def printPoint { println ("Point x location : " + point.x); println ("Point y location : " + point.y); } } } Test.main(null) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 58 / 71
  • 63. Abstract Classes abstract class Shape { // subclass should define this def getArea(): Int } class Circle(r: Int) extends Shape { def getArea(): Int = { r * r * 3 } } val s = new Shape // error: class Shape is abstract val c = new Circle(2) c.getArea Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 59 / 71
  • 64. Traits A class can mix in any number of traits. trait Car { val brand: String } trait Shiny { val shineRefraction: Int } class BMW extends Car with Shiny { val brand = "BMW" val shineRefraction = 12 } Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 60 / 71
  • 65. Generic Types trait Cache[K, V] { def get(key: K): V def put(key: K, value: V) def delete(key: K) } def remove[K](key: K) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 61 / 71
  • 66. Case Classes and Pattern Matching Case classes are used to store and match on the contents of a class. They are designed to be used with pattern matching. You can construct them without using new. scala> case class Calculator(brand: String, model: String) scala> val hp20b = Calculator("hp", "20B") def calcType(calc: Calculator) = calc match { case Calculator("hp", "20B") => "financial" case Calculator("hp", "48G") => "scientific" case Calculator("hp", "30B") => "business" case _ => "Calculator of unknown type" } scala> calcType(hp20b) Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 62 / 71
  • 67. Outline Scala basics Functions Collections Classes and objects SBT Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 63 / 71
  • 68. Simple Build Tool (SBT) An open source build tool for Scala and Java projects. Similar to Java’s Maven or Ant. It is written in Scala. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 64 / 71
  • 69. SBT - Hello World! $ mkdir hello $ cd hello $ cp <path>/HelloWorld.scala . $ sbt ... > run Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 65 / 71
  • 70. Running SBT Interactive mode $ sbt > compile > run Batch mode $ sbt clean run Continuous build and test: automatically recompile or run tests whenever you save a source file. $ sbt > ~ compile Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 66 / 71
  • 71. Common Commands clean: deletes all generated files (in target). compile: compiles the main sources (in src/main/scala). test: compiles and runs all tests. console: starts the Scala interpreter. run <argument>*: run the main class. package: creates a jar file containing the files in src/main/resources and the classes compiled from src/main/scala. help <command>: displays detailed help for the specified command. reload: reloads the build definition (build.sbt, project/*.scala, project/*.sbt files). Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 67 / 71
  • 72. Create a Simple Project Create project directory. Create src/main/scala directory. Create build.sbt in the project root. Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 68 / 71
  • 73. build.sbt A list of Scala expressions, separated by blank lines. Located in the project’s base directory. $ cat build.sbt name := "hello" version := "1.0" scalaVersion := "2.10.3" Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 69 / 71
  • 74. Add Dependencies Add in build.sbt. Module ID format: "groupID" %% "artifact" % "version" % "configuration" libraryDependencies += "org.apache.spark" %% "spark-core" % "0.9.0-incubating" // multiple dependencies libraryDependencies ++= Seq( "org.apache.spark" %% "spark-core" % "0.9.0-incubating", "org.apache.spark" %% "spark-streaming" % "0.9.0-incubating" ) sbt uses the standard Maven2 repository by default, but you can add more resolvers. resolvers += "Akka Repository" at "http://repo.akka.io/releases/" Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 70 / 71
  • 75. Questions? Amir H. Payberah (Tehran Polytechnic) Scala 1393/8/3 71 / 71