scala oo

25
OO with Scala > Vikas Hazrati > [email protected] > @vhazrati

Upload: knoldus-software-llp

Post on 26-May-2015

525 views

Category:

Technology


0 download

DESCRIPTION

OO with Scala by Vikas Hazrati for getting started with ScalaFriday is KnolX day @Knoldus

TRANSCRIPT

Page 1: Scala oo

OO with Scala

> Vikas Hazrati > [email protected] > @vhazrati

Page 2: Scala oo

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

Page 3: Scala oo

Creating Class

New Instance → new KnolX

When no parameters, no parenthesis

Primary constructor called

Page 4: Scala oo

REPL

scala> val k = new KnolX

Add a parameter to the class KnolX

Parameters

(Name:Type) separated by ,

Page 5: Scala oo

REPL

scala> class KnolX(session:String)

Access session

Class parameters result in primary constructor parameters not accessible from outside

Page 6: Scala oo

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

Page 7: Scala oo

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

Page 8: Scala oo

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

Page 9: Scala oo

Defining methods

With def

def minus(that: Time): Int = {...}

Methods have public visibility by default

Return type

Page 10: Scala oo

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

Page 11: Scala oo
Page 12: Scala oo

Operators

Are just methods with zero or one parameter

1.+(2)

Page 13: Scala oo

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

Page 14: Scala oo

REPL

Make your own operator

Page 15: Scala oo

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?

Page 16: Scala oo

Packages

package com.knoldus

Like Java?

Packages truly nest: Members of enclosing packages are visible

Package structure and directory structure may differ

Page 17: Scala oo

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

Page 18: Scala oo

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 }

Page 19: Scala oo

Access Modifiers

class Foo {

protected val bar = "Bar"

}

class Foo {

private val bar = "Bar"

}

Page 20: Scala oo

Singleton Objects

object Foo {

val bar = "Bar"

}

Foo.bar

Used as a replacement for Static in Java

Real objects

Page 21: Scala oo

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

Page 22: Scala oo

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!")

Page 23: Scala oo

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

Page 24: Scala oo

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”

Page 25: Scala oo

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