SlideShare a Scribd company logo
OO with Scala

> Vikas Hazrati > vikas@knoldus.com > @vhazrati
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
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                                 Aux constructors should
                                                        Immediately call another
scala> val t = new Train ("a","b");
                                                        Constructor with this
t: Train = Train@a37825
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 = {...}


                               Return type


Methods have public visibility by default
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
Scala oo
Operators




Are just methods with zero or one parameter

                  1.+(2)
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
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
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
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
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!")
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 out




Case Classes




Pre-condition testing




Companion Objects / Singleton




Access Modifiers, Lazy vals

Ad

More Related Content

What's hot (18)

Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
Tom Flaherty
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Scala
ScalaScala
Scala
Sven Efftinge
 
Scala collections
Scala collectionsScala collections
Scala collections
Inphina Technologies
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
Knoldus Inc.
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Alexey (Mr_Mig) Migutsky
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Core java
Core javaCore java
Core java
Rajkattamuri
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
GauravPatil318
 
Scala categorytheory
Scala categorytheoryScala categorytheory
Scala categorytheory
Knoldus Inc.
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
Meetu Maltiar
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
JUG Lausanne
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Functional Programming in Scala: Notes
Functional Programming in Scala: NotesFunctional Programming in Scala: Notes
Functional Programming in Scala: Notes
Roberto Casadei
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
Hiroshi Ono
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Standard Template Library
Standard Template LibraryStandard Template Library
Standard Template Library
GauravPatil318
 

Viewers also liked (6)

Scala idioms
Scala idiomsScala idioms
Scala idioms
Knoldus Inc.
 
GulpJs - An Introduction
GulpJs - An IntroductionGulpJs - An Introduction
GulpJs - An Introduction
Knoldus Inc.
 
Introduction To Less
Introduction To Less Introduction To Less
Introduction To Less
Knoldus Inc.
 
Backbone js
Backbone jsBackbone js
Backbone js
Knoldus Inc.
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
Knoldus Inc.
 
Backbonejs
BackbonejsBackbonejs
Backbonejs
Knoldus Inc.
 
Ad

Similar to Scala oo (20)

Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyjChapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala collection
Scala collectionScala collection
Scala collection
Knoldus Inc.
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
Arduino Aficionado
 
Imp_Points_Scala
Imp_Points_ScalaImp_Points_Scala
Imp_Points_Scala
Nagavarunkumar Kolla
 
Lab Manual-OOP.pdf
Lab Manual-OOP.pdfLab Manual-OOP.pdf
Lab Manual-OOP.pdf
MUNAZARAZZAQELEA
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
scala.ppt
scala.pptscala.ppt
scala.ppt
Harissh16
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
Mohsen Zainalpour
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189
Mahmoud Samir Fayed
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptx
jkapardhi
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
Piyush Mishra
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
Hermann Hueck
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
elliando dias
 
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptxM251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
Angelo Corsaro
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyjChapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
Chapter4.pptxdgdhgfshsfhtgjsjryjusryjryjursyj
berihun18
 
Principles of functional progrmming in scala
Principles of functional progrmming in scalaPrinciples of functional progrmming in scala
Principles of functional progrmming in scala
ehsoon
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
3Pillar Global
 
The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189The Ring programming language version 1.6 book - Part 33 of 189
The Ring programming language version 1.6 book - Part 33 of 189
Mahmoud Samir Fayed
 
ScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptxScalaLanguage_ch_4_5.pptx
ScalaLanguage_ch_4_5.pptx
jkapardhi
 
Inheritance And Traits
Inheritance And TraitsInheritance And Traits
Inheritance And Traits
Piyush Mishra
 
Type Classes in Scala and Haskell
Type Classes in Scala and HaskellType Classes in Scala and Haskell
Type Classes in Scala and Haskell
Hermann Hueck
 
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptxM251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
M251_Meeting_ jAVAAAAAAAAAAAAAAAAAA.pptx
smartashammari
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip Kumar
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Programming in Scala - Lecture Three
Programming in Scala - Lecture ThreeProgramming in Scala - Lecture Three
Programming in Scala - Lecture Three
Angelo Corsaro
 
Ad

More from Knoldus Inc. (20)

Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-HealingOptimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - HealeniumSelf-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Java 17 features and implementation.pptxJava 17 features and implementation.pptx
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in KubernetesChaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM PresentationGraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime PresentationDAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN PresentationIntroduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Introduction to Argo Rollouts PresentationIntroduction to Argo Rollouts Presentation
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Intro to Azure Container App PresentationIntro to Azure Container App Presentation
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability ExcellenceInsights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis FrameworkCode Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS PresentationAWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and AuthorizationAmazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web DevelopmentZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)Angular Hydration Presentation (FrontEnd)
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-HealingOptimizing Test Execution: Heuristic Algorithm for Self-Healing
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - HealeniumSelf-Healing Test Automation Framework - Healenium
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)Kanban Metrics Presentation (Project Management)
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Java 17 features and implementation.pptxJava 17 features and implementation.pptx
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in KubernetesChaos Mesh Introducing Chaos in Kubernetes
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM PresentationGraalVM - A Step Ahead of JVM Presentation
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)Nomad by HashiCorp Presentation (DevOps)
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime PresentationDAPR - Distributed Application Runtime Presentation
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN PresentationIntroduction to Azure Virtual WAN Presentation
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Introduction to Argo Rollouts PresentationIntroduction to Argo Rollouts Presentation
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Intro to Azure Container App PresentationIntro to Azure Container App Presentation
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability ExcellenceInsights Unveiled Test Reporting and Observability Excellence
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)Introduction to Splunk Presentation (DevOps)
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis FrameworkCode Camp - Data Profiling and Quality Analysis Framework
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS PresentationAWS: Messaging Services in AWS Presentation
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and AuthorizationAmazon Cognito: A Primer on Authentication and Authorization
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web DevelopmentZIO Http A Functional Approach to Scalable and Type-Safe Web Development
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.Managing State & HTTP Requests In Ionic.
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 

Recently uploaded (20)

AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
Build With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdfBuild With AI - In Person Session Slides.pdf
Build With AI - In Person Session Slides.pdf
Google Developer Group - Harare
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent LasterAI 3-in-1: Agents, RAG, and Local Models - Brent Laster
AI 3-in-1: Agents, RAG, and Local Models - Brent Laster
All Things Open
 
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient CareAn Overview of Salesforce Health Cloud & How is it Transforming Patient Care
An Overview of Salesforce Health Cloud & How is it Transforming Patient Care
Cyntexa
 
Bepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firmBepents tech services - a premier cybersecurity consulting firm
Bepents tech services - a premier cybersecurity consulting firm
Benard76
 
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptxReimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
Reimagine How You and Your Team Work with Microsoft 365 Copilot.pptx
John Moore
 
Config 2025 presentation recap covering both days
Config 2025 presentation recap covering both daysConfig 2025 presentation recap covering both days
Config 2025 presentation recap covering both days
TrishAntoni1
 
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Limecraft Webinar - 2025.3 release, featuring Content Delivery, Graphic Conte...
Maarten Verwaest
 
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Crazy Incentives and How They Kill Security. How Do You Turn the Wheel?
Christian Folini
 
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptxTop 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
Top 5 Benefits of Using Molybdenum Rods in Industrial Applications.pptx
mkubeusa
 
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025Zilliz Cloud Monthly Technical Review: May 2025
Zilliz Cloud Monthly Technical Review: May 2025
Zilliz
 
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Optima Cyber - Maritime Cyber Security - MSSP Services - Manolis Sfakianakis ...
Mike Mingos
 
Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?Shoehorning dependency injection into a FP language, what does it take?
Shoehorning dependency injection into a FP language, what does it take?
Eric Torreborre
 
machines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdfmachines-for-woodworking-shops-en-compressed.pdf
machines-for-woodworking-shops-en-compressed.pdf
AmirStern2
 
AI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamsonAI-proof your career by Olivier Vroom and David WIlliamson
AI-proof your career by Olivier Vroom and David WIlliamson
UXPA Boston
 
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdfKit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Kit-Works Team Study_팀스터디_김한솔_nuqs_20250509.pdf
Wonjun Hwang
 
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Kit-Works Team Study_아직도 Dockefile.pdf_김성호
Wonjun Hwang
 
Q1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor PresentationQ1 2025 Dropbox Earnings and Investor Presentation
Q1 2025 Dropbox Earnings and Investor Presentation
Dropbox
 
IT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information TechnologyIT484 Cyber Forensics_Information Technology
IT484 Cyber Forensics_Information Technology
SHEHABALYAMANI
 
Mastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B LandscapeMastering Testing in the Modern F&B Landscape
Mastering Testing in the Modern F&B Landscape
marketing943205
 
Unlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web AppsUnlocking Generative AI in your Web Apps
Unlocking Generative AI in your Web Apps
Maximiliano Firtman
 

Scala oo

  • 1. OO with Scala > Vikas Hazrati > vikas@knoldus.com > @vhazrati
  • 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
  • 3. Creating Class New Instance → new KnolX When no parameters, no parenthesis Primary constructor called
  • 4. REPL scala> val k = new KnolX Add a parameter to the class KnolX Parameters (Name:Type) separated by ,
  • 5. REPL scala> class KnolX(session:String) Access session Class parameters result in primary constructor parameters not accessible from outside
  • 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
  • 9. Defining methods With def def minus(that: Time): Int = {...} Return type Methods have public visibility by default
  • 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
  • 12. Operators Are just methods with zero or one parameter 1.+(2)
  • 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
  • 14. REPL Make your own operator
  • 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?
  • 16. Packages package com.knoldus Like Java? Packages truly nest: Members of enclosing packages are visible Package structure and directory structure may differ
  • 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 }
  • 19. Access Modifiers class Foo { protected val bar = "Bar" } class Foo { private val bar = "Bar" }
  • 20. Singleton Objects object Foo { val bar = "Bar" } Foo.bar Used as a replacement for Static in Java Real objects
  • 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 
  翻译: