OO with Scala, for getting started with Scala.
Scala is a hybrid programming language that implements functional and object-oriented paradigms. With Scala, there is always more than one way to do something and oftentimes it can feel overwhelming.
2. Classes
Classes are blueprints for objects
Use the keyword class to define a class:
class KnolX
Valid Scala code:
No semicolon thanks to semicolon inference
No access modifier, because public visibility is default
No curly braces, since KnolX has no body yet
Classes have public visibility by default
6. Auxiliary Constructors
scala> class Train(number: String) {
| def this() = this("Default")
| def this(n1: String, n2: String) = this(n1 + n2)
|}
defined class Train
scala> val t = new Train
t: Train = Train@3d0083 Aux constructors should
Immediately call another
scala> val t = new Train ("a","b");
Constructor with this
t: Train = Train@a37825
7. Fields out of class parameters
scala> class Train(val kind: String, val number: String)
defined class Train
scala> val t = new Train ("a","b");
t: Train = Train@d4162c
scala> t.kind
res1: String = a
8. REPL
Create a class of your choice
Add parameters to the class without val
Try accessing the fields
Make fields immutable
Try accessing the fields
10. Lazy Vals
Use the keyword lazy to define an immutable field/variable
that is only evaluated on first access:
lazy val asMinutes: Int = ... // Heavy computation
Why should you use lazy?
To reduce initial instantiation time
To reduce initial memory footprint
To resolve initialization order issues
13. scala> class vikas{ REPL
| def +(i:Int, j:Int):Int={i+j}
|}
defined class vikas
scala> val t = new vikas
t: vikas = vikas@f6acd8
scala> t.+(1,2)
res2: Int = 3
scala> t + (1,2)
res3: Int = 3
15. Default Arguments
class Time(val hours: Int = 0, val minutes: Int = 0)
scala> val time = new Time(12)
Result ?
scala> val time = new Time(minutes = 30)
Result?
17. Packages
A single package clause brings only the last (nested) package
into scope:
package com.knoldus
class Foo
Use chained package clauses to bring several last (nested)
packages into scope; here Foo becomes visible without import:
package com.knoldus
package util
class Bar extends Foo
18. Imports
Simple and Single
import com.knoldus.KnolX
All members
import com.knoldus._
Selected, Multiple, Rename
import com.knoldus.{ KnolX, Session }
import java.sql.{ Date => SqlDate }
21. Companion Objects
If a singleton object and a class or trait10 share the same name,
package and file, they are called companions.
object KnolX{}
class KnolX{}
From the class we can access private members of companion
object
22. PreDef
Singleton Object
Commonly Used Types
Predef provides type aliases for types which are commonly used, such as the immutable
collection types Map, Set, and the List constructors (scala.collection.immutable.:: and
scala.collection.immutable.Nil). The types Pair (a Tuple2) and Triple (a Tuple3), with simple
constructors, are also provided.
Console I/O
Predef provides a number of simple functions for console I/O, such as print, println, readLine,
readInt, etc. These functions are all aliases of the functions provided by scala.Console.
Assertions
Defining preconditions
scala> require(1 == 2, "This must obviously fail!")
23. Case Classes
case class Person(name: String)
scala> val person = Person("Joe")
Result?
toString implementation
implementation for hashCode and equals
Class parameters are turned to immutable fields
24. Always a case class?
Sometimes you don’t want the overhead
You cannot inherit a case class from another one
Hint: Case classes are perfect “value objects” but
in most cases not suitable for “service objects”
25. Exercise
Modify the exercise done for the last session on
the basis of this new knowledge.
Try out
Case Classes
Pre-condition testing
Companion Objects / Singleton
Access Modifiers, Lazy vals