2. Why Scala
● Java did wonderful things with its motto of "write
once and run everywhere" but thats half the story
● Abundance of boilerplate in java
● Java provided lower level of abstraction but its very
difficult to write multithreaded applications in java
which runs as expected
● Multi core processors has opened an entire new
dimension in programming world
● Thread safety, Visibility of data(Concurrency)
● Java as a language hasn't evolved much since its
inception but JVM has evolved up to the extent that
its performance has surpassed with native written
code
3. What is Scala
● Scala is port of many years of academic
research on JVM
● SCAlable LAnguage
● Statically typed
○ A variable is bound to a particular type for its lifetime
its type can't be changed and it can only reference
type-compatible instances
○ In dynamic typing the type is bound to a value not
the variable so a variable might refer to a value of
type A then be reassigned to a value of unrelated
type X
○ Ruby, Python, Groovy, Javascript and Smalltalk are
dynamically typed
4. What is Scala
●
●
●
●
●
●
Scripting language
Functional language
Object Oriented language
Concise and flexible syntax
Sophisticated type system
Scalable (performance)
6. Installation
● Unix
○ Command line Download, Extract jar file and add its
"bin" directory in classpath
○ Scala IDE Download
● Windows
○ Command line Download, Extract jar file and add its
"bin" directory in path variable
○ Scala IDE Download
● Other methods
○ Download STS or Eclipse and add scala ide as a
plugin
○ Download Intellij-Idea community version and install
scala as a plugin
7. A taste of Scala
●
●
●
●
●
●
●
●
REPL (Read eval print loop)
$ scala
scala>
scala> :help
scala> :imports
scala> println("Hello World")
scala> printf("%d", 1)
scala> 1 + 2
res0: Int = 3
● scala> 1 + "to string will be called"
res1: String = 1to string will be called
● Scala worksheet in eclipse
8. A taste of Scala Continued ...
class Upper {
def upper(strings : String*) : Seq[String] = {
strings.map((s : String) => s.toUpperCase())
}
}
val up = new Upper
println(up.upper("I", "am", "using", "Scala", "as", "scripting", "language"))
run as - scala upper-script.scala
object Upper {
def main(args : Array[String]) = {
args.map((s : String) => s.toUpperCase()).foreach(printf("%s ", _))
println("")
}
}
run as - scalac upper.scala
scala -cp . Upper I am using scala from compiled file
9. Type less do more
● No Semicolons
○ Fewer characters to clutter your code
○ Increases code readability by breaking statements in
separate line
● Curly braces are not mandatory in all cases
○ class A
○ def add(a : Int, b : Int) = a + b
● 'return' keyword is optional
● Method without parentheses and dots
○
○
○
○
"hello".length() vs "hello".length vs "hello" length
1. +(2) vs 1 + 2
def isEven(n : Int) = n % 2 == 0
List(1,2,3,4) filter isEven foreach println
● if statements are expressions in scala so there
is no special ternary conditional expression
10. Variable declaration
● val
○ immutable (read only)
○ scala> val array : Array[String] = new Array(5)
scala> array(0) = "Hello"
scala> array
○ scala> val list : List[Int] = List(1,2,3)
scala> 23 :: list
scala> list
● var
○ mutable
○ can assign a new value as often as you want
● Both val and var must be initialized when declared
●
except in abstract types and constructor arguments
Scala encourages you to use immutable variables
whenever possible
11. Literals
● Integer literals
○ Byte, Char, Short, Int, Long
○ 'l' or 'L' is required for Long
● Floating-Point literals
○ Float, Double
○ 'f' or 'F' is required for Float
○ 'd' or 'D' is optional for Double
● Boolean (true, false)
● Character literals
○ Printable unicode character or an escape sequence
written between single quotes. Try 'u0041'
● String literals
○ Sequence of characters enclosed in double quotes or
triples of double quotes. Try "Tabtis escaped", """Tabtis
not escaped in triples of double quotes"""
12. Literals Continued ...
● Symbol literals
○ symbols are single quote followed by a letter
followed by zero or more digits or letters
○ these are interned strings meaning two symbols with
same name will actually refer to same objects.
○ Try 'id, '1
○ Not used much in scala but popular in other
languages like Ruby, Smalltalk and Lisp
● Tuples
○ To return multiple values in java either pass it in
method parameters or return a object or a class
which contains these values
○ scala has built in support for tuples of members from
1 to 22
13. Literals Continued ...
● Function literals
○ Function literal is an alternate syntax to define a
function
○ val add = (a : Int, b : Int) => a + b
○ val test = () => System.getProperty("user.dir")
○ Useful for passing as argument in higher order
functions
● Other literals
○ List
■ val v1 = Nil
■ val fruit = List("orange", "mango")
○ Map
■ val stateCapital = Map("UP" -> "Lucknow",
"Bihar" -> "Patna")
■ val districtCount = Map(("UP", 84), ("Bihar", 40))
14. Identifirs
● Scala allows all printable ASCII characters
except parenthetical characters ( ) [ ] { } and
delimeter characters ` ' " . , ;
● It also allows operator characters such as + - %
/ < > etc
● Reserved words can't be used
● Underscore is important it tells the compiler to
treat all characters up to next whitespace as
part of identifier
● After underscore you can have either letters and
digits or a sequence of operator characters but
you can't mix them with letters and digits
● An identifier can also be arbitrary string
between two back quote characters
15. Classes
class Person(firstName : String, lastName : String, age : Int) {}
● Primary Constructor - defined with class declaration
● Auxiliary Constructor - defined as a method this(.....)
● Constructor arguments can have access modifier such as
●
●
private, protected etc.
Arguments in primary constructor becomes instance
variables with setters and getters automatically generated
depending upon variable scope, like val, var private,
protected.
Methods, instance variables can be overridden in subclass
using override keyword Example: 'override def toString = "" '
16. Classes continued ...
Subclass must extend one of the constructor of superclass
class Person(name : String, val age : Int) {
def this() = this("No name", 25)
def incrementAge(value : Int) = age += value
}
// Extending primary constructor
class SmartPerson(name : String, override val age : Int) extends
Person(name, age)
*** override keyword is must with vals
// Extending Auxiliary constructor
class UnknownPerson extends Person {
override def incrementAge(value : Int) = {
if(value > 0) super.incrementAge(value) else throw new
Error("Value can't be < 0)
17. Method declaration
● Starts with a def keyword followed by
optional argument list, a colon character and
the return type of the method, an equal sign
and finally the method body
● Method arguments can have default value
● Method parameter order can be changed by
caller
● Method definition can also be nested
18. Abstract Class
● Starts with abstract keyword, It can have both primary and auxiliary
constructors
● If a method doesn't have a body then it automatically becomes
abstract same for instance variables
● Abstract method must only be declared in abstract class or traits
but not in concrete class
● Abstract class may not contain any abstract method or field but its
subclass must override all abstract members except if it another
abstract class or trait
abstract class Vehicle(val model : String) {
val engineNumber : String
var fuel : Double
def addFuel(amount : Double) }
class Car(override val model : String) extends Vehicle(model) {
val engineNumber = "dfdf"
var fuel = 0
def addFuel(amount : Double) ... }
19. equals and hashcode
● java 'equals' equivalent in scala is 'eq'
● See Scala Source Code
● Scala provides 3 methods for checking equality of
objects/references
● eq -> final method in AnyRef, checks equal reference
● equals -> calls eq in AnyRef, must override it if you want to
check object equality instead of reference equality, structure
def equals(that : Any) "that must be Any"
● == -> final method which calls equals with null checked
● ne -> anti of eq
● must override hashcode whenever overriding equals
● Example in Person class
20. Companion Object
● A way to create singleton object, and separate class level
stuffs with object level stuff
● starts with 'object' keyword in place of 'class' in class
declaration except that it has only default constructor
● It must be defined in same file with same name as actual
class for which it is a companion object
● apply, unapply methods
class Rational(x: Int, y: Int) { ... }
object Rational {
def apply(x : Int, y : Int) = new Rational(x, y)
def unapply(rational : Rational) = if(rational == null) None else
Some(rational.numer, rational.denom)
● Now we can define
val rational = Rational(23, 45)
val Rational(x : Int, y : Int) = Rational(4, 5)
21. Use of None instead of null
● Scala discourages the use of null to avoid
NullPointerException or unnecessary null check
● It provides two implementations of Option[+A] sealed
abstract class
● None -> container has no value
● Some -> container has some value
● If a method can return null then it must be returned as Option
[A]
● Always try to use getORElse rather than get
Example:
scala> var x : Option[String] = None
scala> x.get
scala> x.getOrElse("No Value")
scala> x = Some("has some value")
scala> x.getOrElse("No Value")
scala> x = Option(null)
scala> x = Option("Something")
23. Traits
● Same as java interfaces with ability to have
implementation of methods and variable
declaration
● It solves boilerplate code generated with using
java interface
● It also gives ability to compose behaviour on
demand
trait Culture
trait SouthIndianCulture extends Culture
trait BihariCulture extends Culture
trait ModernCulture extends Culture
class Person extends Culture
val mukesh = new Person with BihariCulture with ModernCulture
val modernPerson = new Person with ModernCulture
val idiot = new Person
24. Traits Contd ...
● Traits can't have primary or auxiliary constructors
● A class can mixin multiple traits using "with" keyword except first
trait starts with "extends"
● It has a well defined algorithm for the order in which it is called
when a class is mixed in with multiple traits
● It provides late binding "super call from a trait depends upon the
order in which it is mixing in"
trait A
trait B extends A
trait C extends B
class D extends A with B with C
*Start with Class and then from right to left write its name expand if needed
D
- The class
DCBA
- Expande C
D C B A B A - Expand B
D C B A B A A - Expand A
Now starting from right keep first one and remove any other repetition of that type
D C B A ScalaObject AnyRef Any - This will be final call order
25. Traits Contd ...
● Traits can extend a class, abstract class which has no
parameter primary or auxiliary constructor
● self type - mechanism to refer to "this"
trait T1
trait T2 {
self =>
}
trait T3 {
self : T1 =>
}
// fine
class C extends T2
// Compilation error, it must extend T1 because it was force in //
definition of T3
class C1 extends T3
26. Types
● Type is a set of information the compiler knows which is
used to infer whether a statement will succeed or fail
● In Scala A type can be one of object, class, trait or
defined with type keyword
● class and trait types are accessible directly but object
types are accessed with objectname.type
● Structural type defines what method/variable signature
you might expect on a particular type. It should be
avoided as it uses reflection
Example
object O
type abstractType
type concreteType = String
type concreteType = C with T
type objectType = O.type
27. Structural Types
// A type closeable must have close method
type Closeable = {def close : Unit}
// Define a method with parameter closeable
def testClose(closeable : Closeable) = closeable.close
// We can call this method on any class or trait which has
// close method in its scope, above method is applicable for all three
class C {
def close = println("closing in C")
}
trait T {
def close = println("closing in T")
}
class C1 extends T