SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
(c) 2013
All rights reserved
Oliver Szymanski
Source-Knights.com
jsxp.org
Scala
Copyright © 2010 Source-Knights.com
Oliver
• Independent Java Enterprise Consultant
• jsxp.org and source-knights.com
• One of the founders of the Association of Java User Groups (ijug.eu)
• Speaker on conferences
• JavaOne, DOAG, JAX, SourceTalk, ...
• Author for IT-magazines
• Writer (Fantasy, Thriller, Science Fiction)
oliver-szymanski.de
Copyright © 2010 Source-Knights.com
Overview
• Basics
• Data types
• Tuples
• Exceptions
• Modifiers
• Special Types
• Operators
• Code flow
• Classes
• Functions
• Matching
Copyright © 2010 Source-Knights.com
Basics
• Data types
• literals like
3.5 or 3.5d or 3.5D (double), 6 (integer), 3.5f or 3.5F (float)
• Basic types:
Byte, Short, Int, Long, Float, Double, Char, String, Boolean
• String Blocks: println("""Welcome to Simply Scala.
Click 'About' for more information.""")
• Alias: type MyAlias = String => Int
• Type intererence: only local
Copyright © 2010 Source-Knights.com
Basics
• Tuples
• val pair = ("answer", 42) // type: (String, Int)
pair._1 // "answer"
pair._2 // 42
• val (i,c)=(1,'a') // careful with the brackets on the left side
• Tuples are in reality case classes:
• case class Tuple2[A, B](_1: A, _2: B)
• Special syntax: tuple with x1, ..., xn can be written (x1, ..., xn)
• Example:
• def divmod(x: Int, y: Int) = new Tuple2[Int, Int](x / y, x % y)
Copyright © 2010 Source-Knights.com
Basics
• Exceptions
• no checked exceptions in Scala
• use throws annotation such that Java code can catch exception
• @throws(classOf[IOException])
Copyright © 2010 Source-Knights.com
Basics
• Modifiers
• Annotations, each on their own line (lower case name), some
java ones might be upper case
• Override modifier (override)
• Access modifier (protected, private)
(also with [packagenames, classnames or this]
• Final modifier (final)
Copyright © 2010 Source-Knights.com
Basics
• Special types
• Nothing (sub type of all other types)
• Null (sub type of all reference types)
• Unit (empty return type)
Copyright © 2010 Source-Knights.com
Basics
• Operators
• Colon/Doublepoint
• The associativity of an operator is determined by its last character:
Right-associative if ending with :
Left-associative otherwise.
• x :: y :: z = x :: (y :: z) whereas x + y + z = (x + y) + z
• x :: y = y.::(x) whereas x + y = x.+(y)
Copyright © 2010 Source-Knights.com
Code flow
• If condition: val try1 = if (1==2) 8 else 9 // equals
• while(total < 17) total += 3
• do { total+=3} while (total < 17)
• for(i <- 1 to 4) println("all four")
• for(i <- 1 until 4 ; j <- 1 to 3) println(i, j)
• for(c<-"hello") println(c) // collections
• for (i <- List.range(from, to) if i % 2 == 0) yield i
// for-comprehension for constructing a list
Copyright © 2010 Source-Knights.com
Example: Own loop
object Loop extends App {
def loop(body: => Unit): LoopUnlessCond = new LoopUnlessCond(body)
protected class LoopUnlessCond(body: => Unit) {
  def unless(cond: => Boolean) {
    body
    if (!cond) unless(cond)
  }
}
var i = 10
loop {
  println("i = " + i)
  i -= 1
} unless (i == 0)
}
Copyright © 2010 Source-Knights.com
Classes
• should be named in the CamelCase
• scala.AnyRef is base topmost class
class Point(ix:Int,iy:Int) {
var x = ix
var y = iy
}
class Point {
var x = 0
var y = 0
}
val p = new Point
p.x = 3
p.y = 4
Copyright © 2010 Source-Knights.com
Classes
// precondition, triggering an IllegalArgumentException
require(y > 0, "y must be positive")
// auxiliary constructor
def this(x: Int) = { ... }
// private method
private def test(a: Int): Int = { ... }
// allow access to package/subpackages/classes
protected[packagename] def test2(a: Int): Int = { ... }
// allow access to subclasses but only same instance
protected[this] def test3(a: Int): Int = { ... }
// overridden method
override def toString = { member1 + ", " + member2 }
Copyright © 2010 Source-Knights.com
Methods
class Point(ix:Int, iy:Int) {
var x = ix
var y = iy
def +(newpt:Point):Point = {
new Point(x+newpt.x, y+newpt.y)
}
}
Copyright © 2010 Source-Knights.com
Traits
trait HasXString {
val x : String // abstract field (no value)
}
trait Ord {
def < (that: Any): Boolean // this is an abstract method
def <=(that: Any): Boolean = (this < that) || (this == that)
def > (that: Any): Boolean = !(this <= that)
def >=(that: Any): Boolean = !(this < that)
}
Copyright © 2010 Source-Knights.com
Traits
class Date(y: Int, m: Int, d: Int) extends Ord {
def year = y
def month = m
def day = d
//Implement the abstract trait method
def <(that: Any): Boolean = {
if (!that.isInstanceOf[Date]) error("cannot compare”)
val o = that.asInstanceOf[Date]
// latest expression is return value
(year < o.year) || (year == o.year && (month < o.month ||
(month == o.month && day < o.day)))
}
Copyright © 2010 Source-Knights.com
Mixin
• def foo(bar: Cloneable with Resetable): Cloneable = { /*...*/ }
• class Iter extends StringIterator(args(0)) with RichIterator
• first parent is called thesuperclass of Iter, whereas the second
(and every other, if present) parent is called a mixin.
Copyright © 2010 Source-Knights.com
Case Classes
• case class Sum(l: Tree, r: Tree) extends Tree
• auto creation of a toString method, copy methods, equals
and hashCode methods, getter methods for construction
parameters
• creates Companion object with factory methods to avoid
“new” operator
Copyright © 2010 Source-Knights.com
Companion objects
• single instance Objects can be defined like
object Bar {
def apply(foo: String) = new Bar(foo)
}
• We speak of a companion object if same name as a class
• usually used as a factory
• as a class does not have static members use companion
objects instead
Copyright © 2010 Source-Knights.com
Parameters
• Named parameters and default values
class HashMap[K,V](initialCapacity:Int = 16, loadFactor:Float = 0.75) {...}
// Uses the defaults
val m1 = new HashMap[String,Int]
// initialCapacity 20, default loadFactor
val m2= new HashMap[String,Int](20)
// overriding both
val m3 = new HashMap[String,Int](20,0.8)
// override only the loadFactory via
// named arguments
val m4 = new HashMap[String,Int](loadFactor = 0.8)
Copyright © 2010 Source-Knights.com
Functions
• defined with def keyword
• usually having parameters and a return type
• return type can be guessed (not if recursion)
• Tuples are possible, use “Unit” as empty return type
def isDivisibleBy(k: Int): Int => Boolean = {
println("evaluating isDivisibleBy")
i => i % k == 0
}
val isEven = isDivisibleBy(2) // only calls isDivisibeBy once
def isEven = isDivisibleBy(2) // calls isDivisibleBy everytime
isEven(9)
Copyright © 2010 Source-Knights.com
Functions
• Functions are technically an object with an apply method
• val func = (x) => x + 1 // creates a function object
• def func = (x) => x + 1 // creates a function (or method in
class context)
• A Function is a set of traits
• Specifically, a function that takes one argument is an instance
of a Function1 trait.
scala> object addOne extends Function1[Int, Int] {
def apply(m: Int): Int = m + 1 }
defined module addOne
A nice short-hand for extends Function1[Int, Int] is extends (Int => Int)
Copyright © 2010 Source-Knights.com
Functions
//Anonymous functions
(x: Int) => x + 1
val addOne = (x: Int) => x + 1
// Function as parameter
filter(lst, (x:String) => x.length() > 3)
def filter(inLst:List[Int],cond:(Int)=>Boolean):List[Int]={
if(inLst==Nil) Nil
else if(cond(inLst.head)) inLst.head::filter(inLst.tail,cond)
else filter(inLst.tail,cond)
}
Copyright © 2010 Source-Knights.com
More features with function
Currying:
def f(a: Int, b: Int): Int // uncurried version (uncurried type is (Int, Int) => Int)
def f(a: Int)(b: Int): Int // curried version (curried type is Int => Int => Int)
def g = f(2)
Higher Order functions: using functions as parameters and returning a
function
Composition of functions with f compose g or f andThen g is possible
Copyright © 2010 Source-Knights.com
Evaluation rules
• def example = a+b // evaluated when called
• val example = a+b // evaluated immediately
• lazy val example = a +b // evaluated once when needed
• def square(x: Double) // call by value
• def square(x: => Double) // call by name
• evaluates the function first, and then evaluates the arguments if
need be
• avoids evaluation of arguments when the parameter is not used
at all by the function.
Copyright © 2010 Source-Knights.com
Matching
• each case is a Partial Function
def decode(n:Int){
println(n match {
case 1 => "One"
case 2 => "Two"
case 3 => "Three"
case _ => "Error" // _ is wildcard, like default
} ) }
Copyright © 2010 Source-Knights.com
Matching
• Pattern matching can be used with match
val res1 = Option(3)
// We want to multiply the number by 2, otherwise return 0.
val result = if (res1.isDefined) { res1.get * 2 } else { 0 }
// getOrElse lets you easily define a default value.
val result = res1.getOrElse(0) * 2
// Pattern matching fits naturally with Option.
val result = res1 match {
case Some(n) => n * 2
case None => 0
}
Copyright © 2010 Source-Knights.com
Outlook
• Collections
• methods: map, foreach, filter, zip, partition, find, drop,
foldLeft, flatten, flatMap...
• even concurrent collections for parallel processing
• Immutable/Mutable
• side effects, predictability, multi-threading
• Streams (like List, but tail is evaluated only on demand)
• Generics
• Implicits/Views
• classes/objects/functions/parameters...
Copyright © 2010 Source-Knights.com
Critics
Copyright © 2010 Source-Knights.com
Agile Tour London
• Friday 1st November 2013
• Combine the holiday for a long weekend in London ;)
• http://www.agiletourlondon.co.uk
Copyright © 2013 Source-Knights.com
Thxalot
Question?
oliver.szymanski@source-knights.com
(c) 2013
All rights reserved

Contenu connexe

Tendances

Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation xShahjahan Samoon
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUIBongwon Lee
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationJacopo Mangiavacchi
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanJimin Hsieh
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array ListPawanMM
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)allanh0526
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesDebasish Ghosh
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Conceptsmdfkhan625
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Kel Cecil
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 

Tendances (20)

Python3
Python3Python3
Python3
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
String and string manipulation x
String and string manipulation xString and string manipulation x
String and string manipulation x
 
Python: Basic Inheritance
Python: Basic InheritancePython: Basic Inheritance
Python: Basic Inheritance
 
Swift in SwiftUI
Swift in SwiftUISwift in SwiftUI
Swift in SwiftUI
 
Oop concepts in python
Oop concepts in pythonOop concepts in python
Oop concepts in python
 
Cats in Scala
Cats in ScalaCats in Scala
Cats in Scala
 
Swift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML PersonalizationSwift for TensorFlow - CoreML Personalization
Swift for TensorFlow - CoreML Personalization
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Intermediate JavaScript
Intermediate JavaScriptIntermediate JavaScript
Intermediate JavaScript
 
Introduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf TaiwanIntroduction to Scala for JCConf Taiwan
Introduction to Scala for JCConf Taiwan
 
Session 15 - Collections - Array List
Session 15 - Collections - Array ListSession 15 - Collections - Array List
Session 15 - Collections - Array List
 
From android/java to swift (3)
From android/java to swift (3)From android/java to swift (3)
From android/java to swift (3)
 
Xtext Eclipse Con
Xtext Eclipse ConXtext Eclipse Con
Xtext Eclipse Con
 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
 
Core Java Concepts
Core Java ConceptsCore Java Concepts
Core Java Concepts
 
Grammarware Memes
Grammarware MemesGrammarware Memes
Grammarware Memes
 
Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!Hey! There's OCaml in my Rust!
Hey! There's OCaml in my Rust!
 
Java
Java Java
Java
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 

En vedette

Python for Beginners - How to Learn Python Easily
Python for Beginners - How to Learn Python EasilyPython for Beginners - How to Learn Python Easily
Python for Beginners - How to Learn Python EasilyCorey McCreary
 
Python interview question for students
Python interview question for studentsPython interview question for students
Python interview question for studentsCorey McCreary
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014Julien Le Dem
 
Sparkcamp @ Strata CA: Intro to Apache Spark with Hands-on Tutorials
Sparkcamp @ Strata CA: Intro to Apache Spark with Hands-on TutorialsSparkcamp @ Strata CA: Intro to Apache Spark with Hands-on Tutorials
Sparkcamp @ Strata CA: Intro to Apache Spark with Hands-on TutorialsDatabricks
 
Apache Spark Introduction - CloudxLab
Apache Spark Introduction - CloudxLabApache Spark Introduction - CloudxLab
Apache Spark Introduction - CloudxLabAbhinav Singh
 
Intro to apache spark stand ford
Intro to apache spark stand fordIntro to apache spark stand ford
Intro to apache spark stand fordThu Hiền
 
Why Scala for Web 2.0?
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?Alex Payne
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInVitaly Gordon
 
Why Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldWhy Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldDean Wampler
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark TutorialAhmet Bulut
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 
Introduction to Apache Spark
Introduction to Apache SparkIntroduction to Apache Spark
Introduction to Apache SparkRahul Jain
 
The skeletal system (slide show)
The skeletal system (slide show)The skeletal system (slide show)
The skeletal system (slide show)William Banaag
 
Introductory Lecture on photography
Introductory Lecture on photographyIntroductory Lecture on photography
Introductory Lecture on photographyAditya Rao
 
Skeletal system
Skeletal systemSkeletal system
Skeletal systemcoachhuey
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 

En vedette (18)

Scala tutorial
Scala tutorialScala tutorial
Scala tutorial
 
Python for Beginners - How to Learn Python Easily
Python for Beginners - How to Learn Python EasilyPython for Beginners - How to Learn Python Easily
Python for Beginners - How to Learn Python Easily
 
Python interview question for students
Python interview question for studentsPython interview question for students
Python interview question for students
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
 
Sparkcamp @ Strata CA: Intro to Apache Spark with Hands-on Tutorials
Sparkcamp @ Strata CA: Intro to Apache Spark with Hands-on TutorialsSparkcamp @ Strata CA: Intro to Apache Spark with Hands-on Tutorials
Sparkcamp @ Strata CA: Intro to Apache Spark with Hands-on Tutorials
 
Apache Spark Introduction - CloudxLab
Apache Spark Introduction - CloudxLabApache Spark Introduction - CloudxLab
Apache Spark Introduction - CloudxLab
 
Intro to apache spark stand ford
Intro to apache spark stand fordIntro to apache spark stand ford
Intro to apache spark stand ford
 
Why Scala for Web 2.0?
Why Scala for Web 2.0?Why Scala for Web 2.0?
Why Scala for Web 2.0?
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedInScalable and Flexible Machine Learning With Scala @ LinkedIn
Scalable and Flexible Machine Learning With Scala @ LinkedIn
 
Why Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data WorldWhy Scala Is Taking Over the Big Data World
Why Scala Is Taking Over the Big Data World
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Apache Spark Tutorial
Apache Spark TutorialApache Spark Tutorial
Apache Spark Tutorial
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Introduction to Apache Spark
Introduction to Apache SparkIntroduction to Apache Spark
Introduction to Apache Spark
 
The skeletal system (slide show)
The skeletal system (slide show)The skeletal system (slide show)
The skeletal system (slide show)
 
Introductory Lecture on photography
Introductory Lecture on photographyIntroductory Lecture on photography
Introductory Lecture on photography
 
Skeletal system
Skeletal systemSkeletal system
Skeletal system
 
Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 

Similaire à Scala: A brief tutorial

Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developersJim Roepcke
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Tomer Gabel
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, SwiftYandex
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala Knoldus Inc.
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitTomer Gabel
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldWerner Hofstra
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojureAbbas Raza
 
(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
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 

Similaire à Scala: A brief tutorial (20)

Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
Introduction to Python for Plone developers
Introduction to Python for Plone developersIntroduction to Python for Plone developers
Introduction to Python for Plone developers
 
Scala coated JVM
Scala coated JVMScala coated JVM
Scala coated JVM
 
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)Speaking Scala: Refactoring for Fun and Profit (Workshop)
Speaking Scala: Refactoring for Fun and Profit (Workshop)
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Denis Lebedev, Swift
Denis  Lebedev, SwiftDenis  Lebedev, Swift
Denis Lebedev, Swift
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
Functions In Scala
Functions In Scala Functions In Scala
Functions In Scala
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
core java
core javacore java
core java
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereldScala: Functioneel programmeren in een object georiënteerde wereld
Scala: Functioneel programmeren in een object georiënteerde wereld
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
(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?
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
Java introduction
Java introductionJava introduction
Java introduction
 
Java
JavaJava
Java
 

Dernier

"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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
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
 
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
 
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
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 

Dernier (20)

"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
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
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
 
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
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
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
 
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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 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
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 

Scala: A brief tutorial

  • 1. (c) 2013 All rights reserved Oliver Szymanski Source-Knights.com jsxp.org Scala
  • 2. Copyright © 2010 Source-Knights.com Oliver • Independent Java Enterprise Consultant • jsxp.org and source-knights.com • One of the founders of the Association of Java User Groups (ijug.eu) • Speaker on conferences • JavaOne, DOAG, JAX, SourceTalk, ... • Author for IT-magazines • Writer (Fantasy, Thriller, Science Fiction) oliver-szymanski.de
  • 3. Copyright © 2010 Source-Knights.com Overview • Basics • Data types • Tuples • Exceptions • Modifiers • Special Types • Operators • Code flow • Classes • Functions • Matching
  • 4. Copyright © 2010 Source-Knights.com Basics • Data types • literals like 3.5 or 3.5d or 3.5D (double), 6 (integer), 3.5f or 3.5F (float) • Basic types: Byte, Short, Int, Long, Float, Double, Char, String, Boolean • String Blocks: println("""Welcome to Simply Scala. Click 'About' for more information.""") • Alias: type MyAlias = String => Int • Type intererence: only local
  • 5. Copyright © 2010 Source-Knights.com Basics • Tuples • val pair = ("answer", 42) // type: (String, Int) pair._1 // "answer" pair._2 // 42 • val (i,c)=(1,'a') // careful with the brackets on the left side • Tuples are in reality case classes: • case class Tuple2[A, B](_1: A, _2: B) • Special syntax: tuple with x1, ..., xn can be written (x1, ..., xn) • Example: • def divmod(x: Int, y: Int) = new Tuple2[Int, Int](x / y, x % y)
  • 6. Copyright © 2010 Source-Knights.com Basics • Exceptions • no checked exceptions in Scala • use throws annotation such that Java code can catch exception • @throws(classOf[IOException])
  • 7. Copyright © 2010 Source-Knights.com Basics • Modifiers • Annotations, each on their own line (lower case name), some java ones might be upper case • Override modifier (override) • Access modifier (protected, private) (also with [packagenames, classnames or this] • Final modifier (final)
  • 8. Copyright © 2010 Source-Knights.com Basics • Special types • Nothing (sub type of all other types) • Null (sub type of all reference types) • Unit (empty return type)
  • 9. Copyright © 2010 Source-Knights.com Basics • Operators • Colon/Doublepoint • The associativity of an operator is determined by its last character: Right-associative if ending with : Left-associative otherwise. • x :: y :: z = x :: (y :: z) whereas x + y + z = (x + y) + z • x :: y = y.::(x) whereas x + y = x.+(y)
  • 10. Copyright © 2010 Source-Knights.com Code flow • If condition: val try1 = if (1==2) 8 else 9 // equals • while(total < 17) total += 3 • do { total+=3} while (total < 17) • for(i <- 1 to 4) println("all four") • for(i <- 1 until 4 ; j <- 1 to 3) println(i, j) • for(c<-"hello") println(c) // collections • for (i <- List.range(from, to) if i % 2 == 0) yield i // for-comprehension for constructing a list
  • 11. Copyright © 2010 Source-Knights.com Example: Own loop object Loop extends App { def loop(body: => Unit): LoopUnlessCond = new LoopUnlessCond(body) protected class LoopUnlessCond(body: => Unit) {   def unless(cond: => Boolean) {     body     if (!cond) unless(cond)   } } var i = 10 loop {   println("i = " + i)   i -= 1 } unless (i == 0) }
  • 12. Copyright © 2010 Source-Knights.com Classes • should be named in the CamelCase • scala.AnyRef is base topmost class class Point(ix:Int,iy:Int) { var x = ix var y = iy } class Point { var x = 0 var y = 0 } val p = new Point p.x = 3 p.y = 4
  • 13. Copyright © 2010 Source-Knights.com Classes // precondition, triggering an IllegalArgumentException require(y > 0, "y must be positive") // auxiliary constructor def this(x: Int) = { ... } // private method private def test(a: Int): Int = { ... } // allow access to package/subpackages/classes protected[packagename] def test2(a: Int): Int = { ... } // allow access to subclasses but only same instance protected[this] def test3(a: Int): Int = { ... } // overridden method override def toString = { member1 + ", " + member2 }
  • 14. Copyright © 2010 Source-Knights.com Methods class Point(ix:Int, iy:Int) { var x = ix var y = iy def +(newpt:Point):Point = { new Point(x+newpt.x, y+newpt.y) } }
  • 15. Copyright © 2010 Source-Knights.com Traits trait HasXString { val x : String // abstract field (no value) } trait Ord { def < (that: Any): Boolean // this is an abstract method def <=(that: Any): Boolean = (this < that) || (this == that) def > (that: Any): Boolean = !(this <= that) def >=(that: Any): Boolean = !(this < that) }
  • 16. Copyright © 2010 Source-Knights.com Traits class Date(y: Int, m: Int, d: Int) extends Ord { def year = y def month = m def day = d //Implement the abstract trait method def <(that: Any): Boolean = { if (!that.isInstanceOf[Date]) error("cannot compare”) val o = that.asInstanceOf[Date] // latest expression is return value (year < o.year) || (year == o.year && (month < o.month || (month == o.month && day < o.day))) }
  • 17. Copyright © 2010 Source-Knights.com Mixin • def foo(bar: Cloneable with Resetable): Cloneable = { /*...*/ } • class Iter extends StringIterator(args(0)) with RichIterator • first parent is called thesuperclass of Iter, whereas the second (and every other, if present) parent is called a mixin.
  • 18. Copyright © 2010 Source-Knights.com Case Classes • case class Sum(l: Tree, r: Tree) extends Tree • auto creation of a toString method, copy methods, equals and hashCode methods, getter methods for construction parameters • creates Companion object with factory methods to avoid “new” operator
  • 19. Copyright © 2010 Source-Knights.com Companion objects • single instance Objects can be defined like object Bar { def apply(foo: String) = new Bar(foo) } • We speak of a companion object if same name as a class • usually used as a factory • as a class does not have static members use companion objects instead
  • 20. Copyright © 2010 Source-Knights.com Parameters • Named parameters and default values class HashMap[K,V](initialCapacity:Int = 16, loadFactor:Float = 0.75) {...} // Uses the defaults val m1 = new HashMap[String,Int] // initialCapacity 20, default loadFactor val m2= new HashMap[String,Int](20) // overriding both val m3 = new HashMap[String,Int](20,0.8) // override only the loadFactory via // named arguments val m4 = new HashMap[String,Int](loadFactor = 0.8)
  • 21. Copyright © 2010 Source-Knights.com Functions • defined with def keyword • usually having parameters and a return type • return type can be guessed (not if recursion) • Tuples are possible, use “Unit” as empty return type def isDivisibleBy(k: Int): Int => Boolean = { println("evaluating isDivisibleBy") i => i % k == 0 } val isEven = isDivisibleBy(2) // only calls isDivisibeBy once def isEven = isDivisibleBy(2) // calls isDivisibleBy everytime isEven(9)
  • 22. Copyright © 2010 Source-Knights.com Functions • Functions are technically an object with an apply method • val func = (x) => x + 1 // creates a function object • def func = (x) => x + 1 // creates a function (or method in class context) • A Function is a set of traits • Specifically, a function that takes one argument is an instance of a Function1 trait. scala> object addOne extends Function1[Int, Int] { def apply(m: Int): Int = m + 1 } defined module addOne A nice short-hand for extends Function1[Int, Int] is extends (Int => Int)
  • 23. Copyright © 2010 Source-Knights.com Functions //Anonymous functions (x: Int) => x + 1 val addOne = (x: Int) => x + 1 // Function as parameter filter(lst, (x:String) => x.length() > 3) def filter(inLst:List[Int],cond:(Int)=>Boolean):List[Int]={ if(inLst==Nil) Nil else if(cond(inLst.head)) inLst.head::filter(inLst.tail,cond) else filter(inLst.tail,cond) }
  • 24. Copyright © 2010 Source-Knights.com More features with function Currying: def f(a: Int, b: Int): Int // uncurried version (uncurried type is (Int, Int) => Int) def f(a: Int)(b: Int): Int // curried version (curried type is Int => Int => Int) def g = f(2) Higher Order functions: using functions as parameters and returning a function Composition of functions with f compose g or f andThen g is possible
  • 25. Copyright © 2010 Source-Knights.com Evaluation rules • def example = a+b // evaluated when called • val example = a+b // evaluated immediately • lazy val example = a +b // evaluated once when needed • def square(x: Double) // call by value • def square(x: => Double) // call by name • evaluates the function first, and then evaluates the arguments if need be • avoids evaluation of arguments when the parameter is not used at all by the function.
  • 26. Copyright © 2010 Source-Knights.com Matching • each case is a Partial Function def decode(n:Int){ println(n match { case 1 => "One" case 2 => "Two" case 3 => "Three" case _ => "Error" // _ is wildcard, like default } ) }
  • 27. Copyright © 2010 Source-Knights.com Matching • Pattern matching can be used with match val res1 = Option(3) // We want to multiply the number by 2, otherwise return 0. val result = if (res1.isDefined) { res1.get * 2 } else { 0 } // getOrElse lets you easily define a default value. val result = res1.getOrElse(0) * 2 // Pattern matching fits naturally with Option. val result = res1 match { case Some(n) => n * 2 case None => 0 }
  • 28. Copyright © 2010 Source-Knights.com Outlook • Collections • methods: map, foreach, filter, zip, partition, find, drop, foldLeft, flatten, flatMap... • even concurrent collections for parallel processing • Immutable/Mutable • side effects, predictability, multi-threading • Streams (like List, but tail is evaluated only on demand) • Generics • Implicits/Views • classes/objects/functions/parameters...
  • 29. Copyright © 2010 Source-Knights.com Critics
  • 30. Copyright © 2010 Source-Knights.com Agile Tour London • Friday 1st November 2013 • Combine the holiday for a long weekend in London ;) • http://www.agiletourlondon.co.uk
  • 31. Copyright © 2013 Source-Knights.com Thxalot Question? oliver.szymanski@source-knights.com (c) 2013 All rights reserved