SlideShare ist ein Scribd-Unternehmen logo
1 von 28
Downloaden Sie, um offline zu lesen
Programming in Scala
By: http://changingtechblog.blogspot.in/
Why Scala
● Java did wonderful things with its motto of "write
once and run everywhere" but thats half the story
● Abundance of boilerplate in java
● Java provided lower level of abstraction but its very
difficult to write multithreaded applications in java
which runs as expected
● Multi core processors has opened an entire new
dimension in programming world
● Thread safety, Visibility of data(Concurrency)
● Java as a language hasn't evolved much since its
inception but JVM has evolved up to the extent that
its performance has surpassed with native written
code
What is Scala
● Scala is port of many years of academic
research on JVM
● SCAlable LAnguage
● Statically typed
○ A variable is bound to a particular type for its lifetime
its type can't be changed and it can only reference
type-compatible instances
○ In dynamic typing the type is bound to a value not
the variable so a variable might refer to a value of
type A then be reassigned to a value of unrelated
type X
○ Ruby, Python, Groovy, Javascript and Smalltalk are
dynamically typed
What is Scala
●
●
●
●
●
●

Scripting language
Functional language
Object Oriented language
Concise and flexible syntax
Sophisticated type system
Scalable (performance)
JVM Languages

Scala
Other JVM
Languages

JAVA

iconst_1
istore_1
iconst_1
istore_2
iload_1
iload_2
iadd
int2byte
istore_3
iload_3
ireturn

JVM

Clojure, Groovy, JRuby, Jython, Rhino, Fantom, Kotlin ...
see also
Installation
● Unix
○ Command line Download, Extract jar file and add its
"bin" directory in classpath
○ Scala IDE Download

● Windows
○ Command line Download, Extract jar file and add its
"bin" directory in path variable
○ Scala IDE Download

● Other methods
○ Download STS or Eclipse and add scala ide as a
plugin
○ Download Intellij-Idea community version and install
scala as a plugin
A taste of Scala
●
●
●
●
●
●
●
●

REPL (Read eval print loop)
$ scala
scala>
scala> :help
scala> :imports
scala> println("Hello World")
scala> printf("%d", 1)
scala> 1 + 2
res0: Int = 3
● scala> 1 + "to string will be called"
res1: String = 1to string will be called
● Scala worksheet in eclipse
A taste of Scala Continued ...
class Upper {
def upper(strings : String*) : Seq[String] = {
strings.map((s : String) => s.toUpperCase())
}
}
val up = new Upper
println(up.upper("I", "am", "using", "Scala", "as", "scripting", "language"))
run as - scala upper-script.scala
object Upper {
def main(args : Array[String]) = {
args.map((s : String) => s.toUpperCase()).foreach(printf("%s ", _))
println("")
}
}
run as - scalac upper.scala
scala -cp . Upper I am using scala from compiled file
Type less do more
● No Semicolons
○ Fewer characters to clutter your code
○ Increases code readability by breaking statements in
separate line

● Curly braces are not mandatory in all cases
○ class A
○ def add(a : Int, b : Int) = a + b

● 'return' keyword is optional
● Method without parentheses and dots
○
○
○
○

"hello".length() vs "hello".length vs "hello" length
1. +(2) vs 1 + 2
def isEven(n : Int) = n % 2 == 0
List(1,2,3,4) filter isEven foreach println

● if statements are expressions in scala so there
is no special ternary conditional expression
Variable declaration
● val
○ immutable (read only)
○ scala> val array : Array[String] = new Array(5)
scala> array(0) = "Hello"
scala> array
○ scala> val list : List[Int] = List(1,2,3)
scala> 23 :: list
scala> list

● var
○ mutable
○ can assign a new value as often as you want

● Both val and var must be initialized when declared
●

except in abstract types and constructor arguments
Scala encourages you to use immutable variables
whenever possible
Literals
● Integer literals
○ Byte, Char, Short, Int, Long
○ 'l' or 'L' is required for Long

● Floating-Point literals
○ Float, Double
○ 'f' or 'F' is required for Float
○ 'd' or 'D' is optional for Double

● Boolean (true, false)
● Character literals
○ Printable unicode character or an escape sequence
written between single quotes. Try 'u0041'

● String literals
○ Sequence of characters enclosed in double quotes or
triples of double quotes. Try "Tabtis escaped", """Tabtis
not escaped in triples of double quotes"""
Literals Continued ...
● Symbol literals
○ symbols are single quote followed by a letter
followed by zero or more digits or letters
○ these are interned strings meaning two symbols with
same name will actually refer to same objects.
○ Try 'id, '1
○ Not used much in scala but popular in other
languages like Ruby, Smalltalk and Lisp

● Tuples
○ To return multiple values in java either pass it in
method parameters or return a object or a class
which contains these values
○ scala has built in support for tuples of members from
1 to 22
Literals Continued ...
● Function literals
○ Function literal is an alternate syntax to define a
function
○ val add = (a : Int, b : Int) => a + b
○ val test = () => System.getProperty("user.dir")
○ Useful for passing as argument in higher order
functions

● Other literals
○ List
■ val v1 = Nil
■ val fruit = List("orange", "mango")
○ Map
■ val stateCapital = Map("UP" -> "Lucknow",
"Bihar" -> "Patna")
■ val districtCount = Map(("UP", 84), ("Bihar", 40))
Identifirs
● Scala allows all printable ASCII characters
except parenthetical characters ( ) [ ] { } and
delimeter characters ` ' " . , ;
● It also allows operator characters such as + - %
/ < > etc
● Reserved words can't be used
● Underscore is important it tells the compiler to
treat all characters up to next whitespace as
part of identifier
● After underscore you can have either letters and
digits or a sequence of operator characters but
you can't mix them with letters and digits
● An identifier can also be arbitrary string
between two back quote characters
Classes
class Person(firstName : String, lastName : String, age : Int) {}

● Primary Constructor - defined with class declaration
● Auxiliary Constructor - defined as a method this(.....)
● Constructor arguments can have access modifier such as
●

●

private, protected etc.
Arguments in primary constructor becomes instance
variables with setters and getters automatically generated
depending upon variable scope, like val, var private,
protected.
Methods, instance variables can be overridden in subclass
using override keyword Example: 'override def toString = "" '
Classes continued ...
Subclass must extend one of the constructor of superclass
class Person(name : String, val age : Int) {
def this() = this("No name", 25)
def incrementAge(value : Int) = age += value
}
// Extending primary constructor
class SmartPerson(name : String, override val age : Int) extends
Person(name, age)
*** override keyword is must with vals
// Extending Auxiliary constructor
class UnknownPerson extends Person {
override def incrementAge(value : Int) = {
if(value > 0) super.incrementAge(value) else throw new
Error("Value can't be < 0)
Method declaration
● Starts with a def keyword followed by
optional argument list, a colon character and
the return type of the method, an equal sign
and finally the method body
● Method arguments can have default value
● Method parameter order can be changed by
caller
● Method definition can also be nested
Abstract Class
● Starts with abstract keyword, It can have both primary and auxiliary
constructors
● If a method doesn't have a body then it automatically becomes
abstract same for instance variables
● Abstract method must only be declared in abstract class or traits
but not in concrete class
● Abstract class may not contain any abstract method or field but its
subclass must override all abstract members except if it another
abstract class or trait
abstract class Vehicle(val model : String) {
val engineNumber : String
var fuel : Double
def addFuel(amount : Double) }
class Car(override val model : String) extends Vehicle(model) {
val engineNumber = "dfdf"
var fuel = 0
def addFuel(amount : Double) ... }
equals and hashcode
● java 'equals' equivalent in scala is 'eq'
● See Scala Source Code
● Scala provides 3 methods for checking equality of
objects/references
● eq -> final method in AnyRef, checks equal reference
● equals -> calls eq in AnyRef, must override it if you want to
check object equality instead of reference equality, structure
def equals(that : Any) "that must be Any"
● == -> final method which calls equals with null checked
● ne -> anti of eq
● must override hashcode whenever overriding equals
● Example in Person class
Companion Object
● A way to create singleton object, and separate class level
stuffs with object level stuff
● starts with 'object' keyword in place of 'class' in class
declaration except that it has only default constructor
● It must be defined in same file with same name as actual
class for which it is a companion object
● apply, unapply methods
class Rational(x: Int, y: Int) { ... }
object Rational {
def apply(x : Int, y : Int) = new Rational(x, y)
def unapply(rational : Rational) = if(rational == null) None else
Some(rational.numer, rational.denom)

● Now we can define
val rational = Rational(23, 45)
val Rational(x : Int, y : Int) = Rational(4, 5)
Use of None instead of null
● Scala discourages the use of null to avoid
NullPointerException or unnecessary null check
● It provides two implementations of Option[+A] sealed
abstract class
● None -> container has no value
● Some -> container has some value
● If a method can return null then it must be returned as Option
[A]
● Always try to use getORElse rather than get
Example:
scala> var x : Option[String] = None
scala> x.get
scala> x.getOrElse("No Value")
scala> x = Some("has some value")
scala> x.getOrElse("No Value")
scala> x = Option(null)
scala> x = Option("Something")
Discussions
●
●
●
●

List, Vector, Stream
Last session exercises
Package objects
File IO
Traits
● Same as java interfaces with ability to have
implementation of methods and variable
declaration
● It solves boilerplate code generated with using
java interface
● It also gives ability to compose behaviour on
demand
trait Culture
trait SouthIndianCulture extends Culture
trait BihariCulture extends Culture
trait ModernCulture extends Culture
class Person extends Culture
val mukesh = new Person with BihariCulture with ModernCulture
val modernPerson = new Person with ModernCulture
val idiot = new Person
Traits Contd ...
● Traits can't have primary or auxiliary constructors
● A class can mixin multiple traits using "with" keyword except first
trait starts with "extends"
● It has a well defined algorithm for the order in which it is called
when a class is mixed in with multiple traits
● It provides late binding "super call from a trait depends upon the
order in which it is mixing in"
trait A
trait B extends A
trait C extends B
class D extends A with B with C
*Start with Class and then from right to left write its name expand if needed
D

- The class

DCBA

- Expande C

D C B A B A - Expand B
D C B A B A A - Expand A
Now starting from right keep first one and remove any other repetition of that type
D C B A ScalaObject AnyRef Any - This will be final call order
Traits Contd ...
● Traits can extend a class, abstract class which has no
parameter primary or auxiliary constructor
● self type - mechanism to refer to "this"
trait T1
trait T2 {
self =>
}
trait T3 {
self : T1 =>
}
// fine
class C extends T2
// Compilation error, it must extend T1 because it was force in //
definition of T3
class C1 extends T3
Types
● Type is a set of information the compiler knows which is
used to infer whether a statement will succeed or fail
● In Scala A type can be one of object, class, trait or
defined with type keyword
● class and trait types are accessible directly but object
types are accessed with objectname.type
● Structural type defines what method/variable signature
you might expect on a particular type. It should be
avoided as it uses reflection
Example
object O
type abstractType
type concreteType = String
type concreteType = C with T
type objectType = O.type
Structural Types
// A type closeable must have close method
type Closeable = {def close : Unit}
// Define a method with parameter closeable
def testClose(closeable : Closeable) = closeable.close
// We can call this method on any class or trait which has
// close method in its scope, above method is applicable for all three
class C {
def close = println("closing in C")
}
trait T {
def close = println("closing in T")
}
class C1 extends T
Thank You

http://changingtechblog.blogspot.in/

Weitere ähnliche Inhalte

Was ist angesagt?

SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.Ruslan Shevchenko
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#Remik Koczapski
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 CertificationsGiacomo Veneri
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and conceptsNicola Bonelli
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in ScalaRose Toomey
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysKonrad Malawski
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Andrew Petryk
 
Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Randy Scovil
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt FaluoticoWithTheBest
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorialDima Statz
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parametersKnoldus Inc.
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scalaAmuhinda Hungai
 

Was ist angesagt? (20)

SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.SE 20016 - programming languages landscape.
SE 20016 - programming languages landscape.
 
Functional programming with F#
Functional programming with F#Functional programming with F#
Functional programming with F#
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Preparing Java 7 Certifications
Preparing Java 7 CertificationsPreparing Java 7 Certifications
Preparing Java 7 Certifications
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Google06
Google06Google06
Google06
 
Practical type mining in Scala
Practical type mining in ScalaPractical type mining in Scala
Practical type mining in Scala
 
Scala functions
Scala functionsScala functions
Scala functions
 
Scala Types of Types @ Lambda Days
Scala Types of Types @ Lambda DaysScala Types of Types @ Lambda Days
Scala Types of Types @ Lambda Days
 
Cat's anatomy
Cat's anatomyCat's anatomy
Cat's anatomy
 
Dart workshop
Dart workshopDart workshop
Dart workshop
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3Objective-C to Swift - Swift Cloud Workshop 3
Objective-C to Swift - Swift Cloud Workshop 3
 
Scala syntax analysis
Scala syntax analysisScala syntax analysis
Scala syntax analysis
 
Optionals by Matt Faluotico
Optionals by Matt FaluoticoOptionals by Matt Faluotico
Optionals by Matt Faluotico
 
A Scala tutorial
A Scala tutorialA Scala tutorial
A Scala tutorial
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
 
Implicit conversion and parameters
Implicit conversion and parametersImplicit conversion and parameters
Implicit conversion and parameters
 
Introduction to programming in scala
Introduction to programming in scalaIntroduction to programming in scala
Introduction to programming in scala
 

Andere mochten auch

The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
Знакомьтесь, Kotlin
Знакомьтесь, KotlinЗнакомьтесь, Kotlin
Знакомьтесь, KotlinTech Talks @NSU
 
Android opetuksessa 11.9.14
Android opetuksessa 11.9.14Android opetuksessa 11.9.14
Android opetuksessa 11.9.14Matleena Laakso
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugsComputer Science Club
 
Infinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using KotlinInfinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using KotlinInfinum
 
Do Languages Matter?
Do Languages Matter?Do Languages Matter?
Do Languages Matter?Bruce Eckel
 
Kotlin в production. Как и зачем?
Kotlin в production. Как и зачем?Kotlin в production. Как и зачем?
Kotlin в production. Как и зачем?DotNetConf
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?Leonardo Zanivan
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?intelliyole
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
 
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsTMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsIosif Itkin
 
Scala in practice
Scala in practiceScala in practice
Scala in practiceTomer Gabel
 
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...Provectus
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 

Andere mochten auch (20)

The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Знакомьтесь, Kotlin
Знакомьтесь, KotlinЗнакомьтесь, Kotlin
Знакомьтесь, Kotlin
 
Scala Day by Day
Scala Day by DayScala Day by Day
Scala Day by Day
 
Scala
ScalaScala
Scala
 
Android opetuksessa 11.9.14
Android opetuksessa 11.9.14Android opetuksessa 11.9.14
Android opetuksessa 11.9.14
 
20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs20140531 serebryany lecture01_fantastic_cpp_bugs
20140531 serebryany lecture01_fantastic_cpp_bugs
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
Infinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using KotlinInfinum Android Talks #20 - Benefits of using Kotlin
Infinum Android Talks #20 - Benefits of using Kotlin
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Do Languages Matter?
Do Languages Matter?Do Languages Matter?
Do Languages Matter?
 
Kotlin в production. Как и зачем?
Kotlin в production. Как и зачем?Kotlin в production. Как и зачем?
Kotlin в production. Как и зачем?
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?JavaOne 2016 - Kotlin: The Language of The Future For JVM?
JavaOne 2016 - Kotlin: The Language of The Future For JVM?
 
Kotlin: Why Do You Care?
Kotlin: Why Do You Care?Kotlin: Why Do You Care?
Kotlin: Why Do You Care?
 
Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010Introduction à Scala - Michel Schinz - January 2010
Introduction à Scala - Michel Schinz - January 2010
 
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart CastsTMPA-2015: Kotlin: From Null Dereference to Smart Casts
TMPA-2015: Kotlin: From Null Dereference to Smart Casts
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
[Expert Fridays] Java MeetUp - Борис Ташкулов (Teamlead Enterprise): "Почему ...
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 

Ähnlich wie Programming in scala - 1

A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into ScalaNehal Shah
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 
javascript objects
javascript objectsjavascript objects
javascript objectsVijay Kalyan
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaBasuk
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scaladatamantra
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageHossam Ghareeb
 

Ähnlich wie Programming in scala - 1 (20)

A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Railroading into Scala
Railroading into ScalaRailroading into Scala
Railroading into Scala
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala.pdf
Scala.pdfScala.pdf
Scala.pdf
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
Should i Go there
Should i Go thereShould i Go there
Should i Go there
 
Understanding Implicits in Scala
Understanding Implicits in ScalaUnderstanding Implicits in Scala
Understanding Implicits in Scala
 
kotlin-nutshell.pptx
kotlin-nutshell.pptxkotlin-nutshell.pptx
kotlin-nutshell.pptx
 
Scala - core features
Scala - core featuresScala - core features
Scala - core features
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
Swift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming languageSwift Tutorial Part 2. The complete guide for Swift programming language
Swift Tutorial Part 2. The complete guide for Swift programming language
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 

Kürzlich hochgeladen

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 

Kürzlich hochgeladen (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 

Programming in scala - 1

  • 1. Programming in Scala By: http://changingtechblog.blogspot.in/
  • 2. Why Scala ● Java did wonderful things with its motto of "write once and run everywhere" but thats half the story ● Abundance of boilerplate in java ● Java provided lower level of abstraction but its very difficult to write multithreaded applications in java which runs as expected ● Multi core processors has opened an entire new dimension in programming world ● Thread safety, Visibility of data(Concurrency) ● Java as a language hasn't evolved much since its inception but JVM has evolved up to the extent that its performance has surpassed with native written code
  • 3. What is Scala ● Scala is port of many years of academic research on JVM ● SCAlable LAnguage ● Statically typed ○ A variable is bound to a particular type for its lifetime its type can't be changed and it can only reference type-compatible instances ○ In dynamic typing the type is bound to a value not the variable so a variable might refer to a value of type A then be reassigned to a value of unrelated type X ○ Ruby, Python, Groovy, Javascript and Smalltalk are dynamically typed
  • 4. What is Scala ● ● ● ● ● ● Scripting language Functional language Object Oriented language Concise and flexible syntax Sophisticated type system Scalable (performance)
  • 6. Installation ● Unix ○ Command line Download, Extract jar file and add its "bin" directory in classpath ○ Scala IDE Download ● Windows ○ Command line Download, Extract jar file and add its "bin" directory in path variable ○ Scala IDE Download ● Other methods ○ Download STS or Eclipse and add scala ide as a plugin ○ Download Intellij-Idea community version and install scala as a plugin
  • 7. A taste of Scala ● ● ● ● ● ● ● ● REPL (Read eval print loop) $ scala scala> scala> :help scala> :imports scala> println("Hello World") scala> printf("%d", 1) scala> 1 + 2 res0: Int = 3 ● scala> 1 + "to string will be called" res1: String = 1to string will be called ● Scala worksheet in eclipse
  • 8. A taste of Scala Continued ... class Upper { def upper(strings : String*) : Seq[String] = { strings.map((s : String) => s.toUpperCase()) } } val up = new Upper println(up.upper("I", "am", "using", "Scala", "as", "scripting", "language")) run as - scala upper-script.scala object Upper { def main(args : Array[String]) = { args.map((s : String) => s.toUpperCase()).foreach(printf("%s ", _)) println("") } } run as - scalac upper.scala scala -cp . Upper I am using scala from compiled file
  • 9. Type less do more ● No Semicolons ○ Fewer characters to clutter your code ○ Increases code readability by breaking statements in separate line ● Curly braces are not mandatory in all cases ○ class A ○ def add(a : Int, b : Int) = a + b ● 'return' keyword is optional ● Method without parentheses and dots ○ ○ ○ ○ "hello".length() vs "hello".length vs "hello" length 1. +(2) vs 1 + 2 def isEven(n : Int) = n % 2 == 0 List(1,2,3,4) filter isEven foreach println ● if statements are expressions in scala so there is no special ternary conditional expression
  • 10. Variable declaration ● val ○ immutable (read only) ○ scala> val array : Array[String] = new Array(5) scala> array(0) = "Hello" scala> array ○ scala> val list : List[Int] = List(1,2,3) scala> 23 :: list scala> list ● var ○ mutable ○ can assign a new value as often as you want ● Both val and var must be initialized when declared ● except in abstract types and constructor arguments Scala encourages you to use immutable variables whenever possible
  • 11. Literals ● Integer literals ○ Byte, Char, Short, Int, Long ○ 'l' or 'L' is required for Long ● Floating-Point literals ○ Float, Double ○ 'f' or 'F' is required for Float ○ 'd' or 'D' is optional for Double ● Boolean (true, false) ● Character literals ○ Printable unicode character or an escape sequence written between single quotes. Try 'u0041' ● String literals ○ Sequence of characters enclosed in double quotes or triples of double quotes. Try "Tabtis escaped", """Tabtis not escaped in triples of double quotes"""
  • 12. Literals Continued ... ● Symbol literals ○ symbols are single quote followed by a letter followed by zero or more digits or letters ○ these are interned strings meaning two symbols with same name will actually refer to same objects. ○ Try 'id, '1 ○ Not used much in scala but popular in other languages like Ruby, Smalltalk and Lisp ● Tuples ○ To return multiple values in java either pass it in method parameters or return a object or a class which contains these values ○ scala has built in support for tuples of members from 1 to 22
  • 13. Literals Continued ... ● Function literals ○ Function literal is an alternate syntax to define a function ○ val add = (a : Int, b : Int) => a + b ○ val test = () => System.getProperty("user.dir") ○ Useful for passing as argument in higher order functions ● Other literals ○ List ■ val v1 = Nil ■ val fruit = List("orange", "mango") ○ Map ■ val stateCapital = Map("UP" -> "Lucknow", "Bihar" -> "Patna") ■ val districtCount = Map(("UP", 84), ("Bihar", 40))
  • 14. Identifirs ● Scala allows all printable ASCII characters except parenthetical characters ( ) [ ] { } and delimeter characters ` ' " . , ; ● It also allows operator characters such as + - % / < > etc ● Reserved words can't be used ● Underscore is important it tells the compiler to treat all characters up to next whitespace as part of identifier ● After underscore you can have either letters and digits or a sequence of operator characters but you can't mix them with letters and digits ● An identifier can also be arbitrary string between two back quote characters
  • 15. Classes class Person(firstName : String, lastName : String, age : Int) {} ● Primary Constructor - defined with class declaration ● Auxiliary Constructor - defined as a method this(.....) ● Constructor arguments can have access modifier such as ● ● private, protected etc. Arguments in primary constructor becomes instance variables with setters and getters automatically generated depending upon variable scope, like val, var private, protected. Methods, instance variables can be overridden in subclass using override keyword Example: 'override def toString = "" '
  • 16. Classes continued ... Subclass must extend one of the constructor of superclass class Person(name : String, val age : Int) { def this() = this("No name", 25) def incrementAge(value : Int) = age += value } // Extending primary constructor class SmartPerson(name : String, override val age : Int) extends Person(name, age) *** override keyword is must with vals // Extending Auxiliary constructor class UnknownPerson extends Person { override def incrementAge(value : Int) = { if(value > 0) super.incrementAge(value) else throw new Error("Value can't be < 0)
  • 17. Method declaration ● Starts with a def keyword followed by optional argument list, a colon character and the return type of the method, an equal sign and finally the method body ● Method arguments can have default value ● Method parameter order can be changed by caller ● Method definition can also be nested
  • 18. Abstract Class ● Starts with abstract keyword, It can have both primary and auxiliary constructors ● If a method doesn't have a body then it automatically becomes abstract same for instance variables ● Abstract method must only be declared in abstract class or traits but not in concrete class ● Abstract class may not contain any abstract method or field but its subclass must override all abstract members except if it another abstract class or trait abstract class Vehicle(val model : String) { val engineNumber : String var fuel : Double def addFuel(amount : Double) } class Car(override val model : String) extends Vehicle(model) { val engineNumber = "dfdf" var fuel = 0 def addFuel(amount : Double) ... }
  • 19. equals and hashcode ● java 'equals' equivalent in scala is 'eq' ● See Scala Source Code ● Scala provides 3 methods for checking equality of objects/references ● eq -> final method in AnyRef, checks equal reference ● equals -> calls eq in AnyRef, must override it if you want to check object equality instead of reference equality, structure def equals(that : Any) "that must be Any" ● == -> final method which calls equals with null checked ● ne -> anti of eq ● must override hashcode whenever overriding equals ● Example in Person class
  • 20. Companion Object ● A way to create singleton object, and separate class level stuffs with object level stuff ● starts with 'object' keyword in place of 'class' in class declaration except that it has only default constructor ● It must be defined in same file with same name as actual class for which it is a companion object ● apply, unapply methods class Rational(x: Int, y: Int) { ... } object Rational { def apply(x : Int, y : Int) = new Rational(x, y) def unapply(rational : Rational) = if(rational == null) None else Some(rational.numer, rational.denom) ● Now we can define val rational = Rational(23, 45) val Rational(x : Int, y : Int) = Rational(4, 5)
  • 21. Use of None instead of null ● Scala discourages the use of null to avoid NullPointerException or unnecessary null check ● It provides two implementations of Option[+A] sealed abstract class ● None -> container has no value ● Some -> container has some value ● If a method can return null then it must be returned as Option [A] ● Always try to use getORElse rather than get Example: scala> var x : Option[String] = None scala> x.get scala> x.getOrElse("No Value") scala> x = Some("has some value") scala> x.getOrElse("No Value") scala> x = Option(null) scala> x = Option("Something")
  • 22. Discussions ● ● ● ● List, Vector, Stream Last session exercises Package objects File IO
  • 23. Traits ● Same as java interfaces with ability to have implementation of methods and variable declaration ● It solves boilerplate code generated with using java interface ● It also gives ability to compose behaviour on demand trait Culture trait SouthIndianCulture extends Culture trait BihariCulture extends Culture trait ModernCulture extends Culture class Person extends Culture val mukesh = new Person with BihariCulture with ModernCulture val modernPerson = new Person with ModernCulture val idiot = new Person
  • 24. Traits Contd ... ● Traits can't have primary or auxiliary constructors ● A class can mixin multiple traits using "with" keyword except first trait starts with "extends" ● It has a well defined algorithm for the order in which it is called when a class is mixed in with multiple traits ● It provides late binding "super call from a trait depends upon the order in which it is mixing in" trait A trait B extends A trait C extends B class D extends A with B with C *Start with Class and then from right to left write its name expand if needed D - The class DCBA - Expande C D C B A B A - Expand B D C B A B A A - Expand A Now starting from right keep first one and remove any other repetition of that type D C B A ScalaObject AnyRef Any - This will be final call order
  • 25. Traits Contd ... ● Traits can extend a class, abstract class which has no parameter primary or auxiliary constructor ● self type - mechanism to refer to "this" trait T1 trait T2 { self => } trait T3 { self : T1 => } // fine class C extends T2 // Compilation error, it must extend T1 because it was force in // definition of T3 class C1 extends T3
  • 26. Types ● Type is a set of information the compiler knows which is used to infer whether a statement will succeed or fail ● In Scala A type can be one of object, class, trait or defined with type keyword ● class and trait types are accessible directly but object types are accessed with objectname.type ● Structural type defines what method/variable signature you might expect on a particular type. It should be avoided as it uses reflection Example object O type abstractType type concreteType = String type concreteType = C with T type objectType = O.type
  • 27. Structural Types // A type closeable must have close method type Closeable = {def close : Unit} // Define a method with parameter closeable def testClose(closeable : Closeable) = closeable.close // We can call this method on any class or trait which has // close method in its scope, above method is applicable for all three class C { def close = println("closing in C") } trait T { def close = println("closing in T") } class C1 extends T