scala oo
DESCRIPTION
OO with Scala by Vikas Hazrati for getting started with ScalaFriday is KnolX day @KnoldusTRANSCRIPT
Classes
Classes are blueprints for objectsUse the keyword class to define a class:
class KnolX
Valid Scala code:No semicolon thanks to semicolon inferenceNo access modifier, because public visibility is defaultNo curly braces, since KnolX has no body yet
Classes have public visibility by default
Creating Class
New Instance → new KnolX
When no parameters, no parenthesis
Primary constructor called
REPL
scala> val k = new KnolX
Add a parameter to the class KnolX
Parameters
(Name:Type) separated by ,
REPL
scala> class KnolX(session:String)
Access session
Class parameters result in primary constructor parameters not accessible from outside
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
scala> val t = new Train ("a","b");
t: Train = Train@a37825
Aux constructors should Immediately call another Constructor with this
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
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
Defining methods
With def
def minus(that: Time): Int = {...}
Methods have public visibility by default
Return type
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
Operators
Are just methods with zero or one parameter
1.+(2)
REPLscala> class vikas{
| 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
REPL
Make your own operator
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?
Packages
package com.knoldus
Like Java?
Packages truly nest: Members of enclosing packages are visible
Package structure and directory structure may differ
PackagesA 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
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 }
Access Modifiers
class Foo {
protected val bar = "Bar"
}
class Foo {
private val bar = "Bar"
}
Singleton Objects
object Foo {
val bar = "Bar"
}
Foo.bar
Used as a replacement for Static in Java
Real objects
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
PreDefSingleton 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!")
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
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”
Exercise
Modify the exercise done for the last session on the basis of this new knowledge.
Try outCase ClassesPre-condition testingCompanion Objects / SingletonAccess Modifiers, Lazy vals