• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Scala oo
 

Scala oo

on

  • 733 views

OO with Scala by Vikas Hazrati for getting started with Scala

OO with Scala by Vikas Hazrati for getting started with Scala

Friday is KnolX day @Knoldus

Statistics

Views

Total Views
733
Views on SlideShare
730
Embed Views
3

Actions

Likes
1
Downloads
6
Comments
0

2 Embeds 3

http://www.docshut.com 2
http://us-w1.rockmelt.com 1

Accessibility

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Scala oo Scala oo Presentation Transcript

    • OO with Scala> Vikas Hazrati > vikas@knoldus.com > @vhazrati
    • ClassesClasses are blueprints for objectsUse the keyword class to define a class:class KnolXValid Scala code:No semicolon thanks to semicolon inferenceNo access modifier, because public visibility is defaultNo curly braces, since KnolX has no body yetClasses have public visibility by default
    • Creating ClassNew Instance → new KnolXWhen no parameters, no parenthesisPrimary constructor called
    • REPLscala> val k = new KnolXAdd a parameter to the class KnolXParameters(Name:Type) separated by ,
    • REPLscala> class KnolX(session:String)Access sessionClass parameters result in primary constructor parameters not accessible from outside
    • Auxiliary Constructorsscala> class Train(number: String) { | def this() = this("Default") | def this(n1: String, n2: String) = this(n1 + n2) |}defined class Trainscala> val t = new Traint: Train = Train@3d0083 Aux constructors should Immediately call anotherscala> val t = new Train ("a","b"); Constructor with thist: Train = Train@a37825
    • Fields out of class parametersscala> class Train(val kind: String, val number: String)defined class Trainscala> val t = new Train ("a","b");t: Train = Train@d4162cscala> t.kindres1: String = a
    • REPLCreate a class of your choiceAdd parameters to the class without valTry accessing the fieldsMake fields immutableTry accessing the fields
    • Defining methodsWith defdef minus(that: Time): Int = {...} Return typeMethods have public visibility by default
    • Lazy ValsUse the keyword lazy to define an immutable field/variablethat is only evaluated on first access:lazy val asMinutes: Int = ... // Heavy computationWhy should you use lazy?To reduce initial instantiation timeTo reduce initial memory footprintTo resolve initialization order issues
    • OperatorsAre just methods with zero or one parameter 1.+(2)
    • scala> class vikas{ REPL | def +(i:Int, j:Int):Int={i+j} |}defined class vikasscala> val t = new vikast: vikas = vikas@f6acd8scala> t.+(1,2)res2: Int = 3scala> t + (1,2)res3: Int = 3
    • REPLMake your own operator
    • Default Argumentsclass Time(val hours: Int = 0, val minutes: Int = 0)scala> val time = new Time(12)Result ?scala> val time = new Time(minutes = 30)Result?
    • Packagespackage com.knoldusLike Java?Packages truly nest: Members of enclosing packages are visiblePackage structure and directory structure may differ
    • PackagesA single package clause brings only the last (nested) packageinto scope:package com.knoldusclass FooUse chained package clauses to bring several last (nested)packages into scope; here Foo becomes visible without import:package com.knolduspackage utilclass Bar extends Foo
    • ImportsSimple and Singleimport com.knoldus.KnolXAll membersimport com.knoldus._Selected, Multiple, Renameimport com.knoldus.{ KnolX, Session }import java.sql.{ Date => SqlDate }
    • Access Modifiersclass Foo { protected val bar = "Bar"}class Foo { private val bar = "Bar"}
    • Singleton Objectsobject Foo { val bar = "Bar"}Foo.barUsed as a replacement for Static in JavaReal objects
    • Companion ObjectsIf 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
    • PreDef Singleton ObjectCommonly Used TypesPredef 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/OPredef 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.AssertionsDefining preconditionsscala> require(1 == 2, "This must obviously fail!")
    • Case Classescase class Person(name: String)scala> val person = Person("Joe")Result?toString implementationimplementation for hashCode and equalsClass parameters are turned to immutable fields
    • Always a case class?Sometimes you don’t want the overheadYou cannot inherit a case class from another oneHint: Case classes are perfect “value objects” but in most cases not suitable for “service objects”
    • ExerciseModify 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