Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Scala oo


Published on

OO with Scala by Vikas Hazrati for getting started with Scala

Friday is KnolX day @Knoldus

Published in: Technology, Education
  • Be the first to comment

Scala oo

  1. 1. OO with Scala> Vikas Hazrati > > @vhazrati
  2. 2. 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
  3. 3. Creating ClassNew Instance → new KnolXWhen no parameters, no parenthesisPrimary constructor called
  4. 4. REPLscala> val k = new KnolXAdd a parameter to the class KnolXParameters(Name:Type) separated by ,
  5. 5. REPLscala> class KnolX(session:String)Access sessionClass parameters result in primary constructor parameters not accessible from outside
  6. 6. 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
  7. 7. 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
  8. 8. REPLCreate a class of your choiceAdd parameters to the class without valTry accessing the fieldsMake fields immutableTry accessing the fields
  9. 9. Defining methodsWith defdef minus(that: Time): Int = {...} Return typeMethods have public visibility by default
  10. 10. 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
  11. 11. OperatorsAre just methods with zero or one parameter 1.+(2)
  12. 12. 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
  13. 13. REPLMake your own operator
  14. 14. 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?
  15. 15. Packagespackage com.knoldusLike Java?Packages truly nest: Members of enclosing packages are visiblePackage structure and directory structure may differ
  16. 16. 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
  17. 17. ImportsSimple and Singleimport com.knoldus.KnolXAll membersimport com.knoldus._Selected, Multiple, Renameimport com.knoldus.{ KnolX, Session }import java.sql.{ Date => SqlDate }
  18. 18. Access Modifiersclass Foo { protected val bar = "Bar"}class Foo { private val bar = "Bar"}
  19. 19. Singleton Objectsobject Foo { val bar = "Bar"}Foo.barUsed as a replacement for Static in JavaReal objects
  20. 20. 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
  21. 21. 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!")
  22. 22. Case Classescase class Person(name: String)scala> val person = Person("Joe")Result?toString implementationimplementation for hashCode and equalsClass parameters are turned to immutable fields
  23. 23. 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”
  24. 24. 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