SlideShare a Scribd company logo
packagenl.devnology.workshopimportjava.util._classLearnALanguage(today: Calendar) extendsDevnology{ defwelcome(participants: List[Participant]) {participants.foreach(p => println("welcome" + p))  }  def facilitators() = {  Facilitator("SoemirnoKartosoewito")  ::   Facilitator("Jan Willem Tulp") :: Nil  }}
What’s the plan?Setup development environment (Eclipse + Scalaplugin)Form pair-programming pairsExplanation of basic concepts and syntaxLabs, labs, labs...... and of course: share knowledge!
Euh...Scala?Scala runs on JVM and .Net VMintegrates 100% with existing librarieshybrid language: both functional and OOstatically typed“everything is an object”...Immutability, Currying, Tuples, Closures, Higher Order Functions, etc....
Scala in the enterprise
Run Scala as...Interactive / REPL (Read Eval Print Loop): the scala command starts an interactive shellAs scriptCompiled: scalac command compiles Scala codeSee: http://www.scala-lang.org/node/166
Variables, Values & Type Inferencevarmsg = "welcome to ..." // msg is mutablemsg += " Devnology" msg = 3 // compiler error
Variables, Values & Type Inferencevalmsg = "welcome to ..." // msg is immutablemsg += " Devnology" // compiler errorval n : Int = 3 // explicit type declarationvalname : String = "John"
Functionsdef min(x: Int, y: Int) = if (x < y) x else y// equivalent:def invert(x: Int) = -x // last statement is return valuedef invert(x: Int) : Int = { return –x }Unit can be considered as java’s voidWatch out!def invert(x: Int) { // will return Unit, = is absent  -x}
Every operation is a function call1 + 2    is the same as1.+(2)“to” is not a keyword:  for (i <- 0 to 10) print(i)map containsKey ‘a’   is the same as      map.containsKey(‘a’)
Listsvalscores = List(1, 2, 3) // immutablevalextraScores: List[Int] = 4 :: 5 :: 6 :: Nil// allScores = List(1, 2, 3, 4, 5, 6)// scores = List(1, 2, 3)// extraScores = List(4, 5, 6)valallScores = scores ::: extraScoresvalevenMoreScores = 7 :: allScoresNil is synonym for empty list
Foreachvalscores = List(1, 2, 3)// equivalentscores.foreach((n: Int) => println(n))scores.foreach(n => println(n))scores.foreach(println)
For comprehensionsvalscores = List(1, 2, 3)for (s <- scores)println(s)for (s <- scores if s > 1)println(s)
Arraysvalnames = Array("John", "Jane")names(0) = "Richard" // Arrays are mutableval cities = new Array[String](2)cities(0) = "Amsterdam"cities(1) = "Rotterdam"for (i <- 0 to 1)println(cities(i))
Mapsvaltowns = Map("John" -> "Amsterdam", "Jane" -> "Rotterdam") // default immutable Mapvar a = towns("John") // returns "Amsterdam"a = towns get "John”// returns Some(Amsterdam)a = towns get "John"get // returns "Amsterdam"var r = towns("Bill") // throws NoSuchElementExceptionr = towns get "Bill”// returns Nonetowns.update("John", "Delft") // returns a new Map
Classes & Constructorsclass Person(name: String, age: Int) {if (age < 0) thrownewIllegalArgumentExceptiondefsayHello() { println("Hello, " + name) }}class Person(name: String, age: Int) {require (age >= 0)defsayHello() { println("Hello, " + name) }}
Classes & Constructorsclass Person(name: String, age: Int) {def this(name: String) = this(name, 21) // auxiliarydef this(age: Int) = this(“John”, age) // auxiliarydef this() = this(“John”, 21) // auxiliary}
Classes & Constructorsclass Person(name: String, age: Int)...val p = new Person("John", 33)val a = p.age// compiler errorp.name = "Richard" // compiler errorclass Person(var name: String, val age: Int)
Companion Objects// must be declared in same file as Person classobject Person {defprintName = println("John")}valp = Person // Singleton is also an objectPerson.printName// similar to static methods in Java/C#
Traitstrait Student {varage = 10;  def greet() = {"Hello teacher!"  }  def study(): String // abstract method}
Extending Traitsclass FirstGrader extends Student {  override def greet() = {"Hello amazing teacher!"  }  override def study(): String = {“I am studying really hard!"  }}
Trait Mixin// compiler error: abstract function study from trait Student is not implementedvaljohn = new Person with StudenttraitSimpleStudent {def greet() = "Hello amazing teacher!"}// this is okval john = new Person withSimpleStudentprintln(john.greet())
Scala Applicationobject Person  def main(args: Array[String]) { // define a main method    for (arg <- args)println("Hello " + arg)  }}// or extend Application traitobject Person extends Application {   for (name <- List("John", "Jane")) println("Hello " + name)}
Pattern Matchingvalcolor = if (args.length > 0) args(0) else ""valfruit match {case"red"=>"apple"case"orange" =>"orange"case"yellow" =>"banana"case_ => "yuk!"}
Case Classescase class Var(name: String) extendsExprval v = Var("sum")adds a Factory method with the name of the classall parameters implicitly get a val prefix, so they are maintained as fields“natural” implementation of toString, hashCode and equalsbig advantage: support pattern matching
Exceptionstry {args(0).toFloat} catch {  case ex: NumberFormatException => println("Oops!")}
Tuplesvalpair = ("John", 28) // Tuple2[String, Int]println(pair._1)println(pair._2)def divProd(x: Int, y:Int) = (x / y, x * y)valdp = divProd(10, 2)println(pair._1) // 5println(pair._2) // 20
LABS!!Resources:http://www.scala-lang.org/apihttp://scala-tools.org/scaladocs/scala-library/2.7.1/http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugeeshttp://blogs.sun.com/sundararajan/entry/scala_for_java_programmers
THANK YOU!
Ad

Recommended

Php Chapter 2 3 Training
Php Chapter 2 3 Training
Chris Chubb
 
Haxe: What Makes It Cool
Haxe: What Makes It Cool
eddieSullivan
 
The Death of Final Tagless
The Death of Final Tagless
John De Goes
 
Scalaz 8: A Whole New Game
Scalaz 8: A Whole New Game
John De Goes
 
Scala for Java Developers
Scala for Java Developers
RamnivasLaddad
 
High Wizardry in the Land of Scala
High Wizardry in the Land of Scala
djspiewak
 
Practically Functional
Practically Functional
djspiewak
 
PHP Unit 3 functions_in_php_2
PHP Unit 3 functions_in_php_2
Kumar
 
Scala Intro
Scala Intro
Paolo Platter
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
Intro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Demystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
PHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
Introduction To Scala
Introduction To Scala
Peter Maas
 
Scala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
Scala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Refactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
First-Class Patterns
First-Class Patterns
John De Goes
 
A bit about Scala
A bit about Scala
Vladimir Parfinenko
 
Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
Scala uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
Rodolfo Carvalho
 
Sorting arrays in PHP
Sorting arrays in PHP
Vineet Kumar Saini
 
Being functional in PHP
Being functional in PHP
David de Boer
 
Scala for Jedi
Scala for Jedi
Vladimir Parfinenko
 
Cercapaz compendio de_oientaciones para la paz
Cercapaz compendio de_oientaciones para la paz
Erick Bravo
 

More Related Content

What's hot (20)

Scala Intro
Scala Intro
Paolo Platter
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
Intro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Demystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
PHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
Introduction To Scala
Introduction To Scala
Peter Maas
 
Scala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
Scala fundamentals
Scala fundamentals
Alfonso Ruzafa
 
Refactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
First-Class Patterns
First-Class Patterns
John De Goes
 
A bit about Scala
A bit about Scala
Vladimir Parfinenko
 
Introduction in php part 2
Introduction in php part 2
Bozhidar Boshnakov
 
Scala uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
Rodolfo Carvalho
 
Sorting arrays in PHP
Sorting arrays in PHP
Vineet Kumar Saini
 
Being functional in PHP
Being functional in PHP
David de Boer
 
Scala for Jedi
Scala for Jedi
Vladimir Parfinenko
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
Tomer Gabel
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Hipot Studio
 
Intro to Functional Programming in Scala
Intro to Functional Programming in Scala
Shai Yallin
 
Demystifying functional programming with Scala
Demystifying functional programming with Scala
Denis
 
PHP Functions & Arrays
PHP Functions & Arrays
Henry Osborne
 
Introduction To Scala
Introduction To Scala
Peter Maas
 
Scala for ruby programmers
Scala for ruby programmers
tymon Tobolski
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
Bozhidar Boshnakov
 
Refactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
First-Class Patterns
First-Class Patterns
John De Goes
 
Scala uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
O CPAN tem as ferramentas que você precisa para fazer TDD em Perl, o Coding D...
Rodolfo Carvalho
 
Being functional in PHP
Being functional in PHP
David de Boer
 

Viewers also liked (6)

Cercapaz compendio de_oientaciones para la paz
Cercapaz compendio de_oientaciones para la paz
Erick Bravo
 
Great marketing can save the world
Great marketing can save the world
Ian Lurie
 
(a hopefully fairly painless introduction to) Linked Open Data
(a hopefully fairly painless introduction to) Linked Open Data
Tim Sherratt
 
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
Ingrid Dirksen
 
Eindverslag stage Wellness Center Maassluis
Eindverslag stage Wellness Center Maassluis
Lars Bergwerff
 
Cercapaz compendio de_oientaciones para la paz
Cercapaz compendio de_oientaciones para la paz
Erick Bravo
 
Great marketing can save the world
Great marketing can save the world
Ian Lurie
 
(a hopefully fairly painless introduction to) Linked Open Data
(a hopefully fairly painless introduction to) Linked Open Data
Tim Sherratt
 
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
Ingrid Dirksen
 
Eindverslag stage Wellness Center Maassluis
Eindverslag stage Wellness Center Maassluis
Lars Bergwerff
 
Ad

Similar to Scala: Devnology - Learn A Language Scala (20)

Scala introduction
Scala introduction
Alf Kristian Støyle
 
Introduction to Scala
Introduction to Scala
Lorenzo Dematté
 
Scala presentationjune112011
Scala presentationjune112011
PrasannaKumar Sathyanarayanan
 
Scala ntnu
Scala ntnu
Alf Kristian Støyle
 
Scala - brief intro
Scala - brief intro
Razvan Cojocaru
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
SDC - Einführung in Scala
SDC - Einführung in Scala
Christian Baranowski
 
Rewriting Java In Scala
Rewriting Java In Scala
Skills Matter
 
Introduction to Scala
Introduction to Scala
Aleksandar Prokopec
 
Workshop Scala
Workshop Scala
Bert Van Vreckem
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4
Emil Vladev
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Scala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Rewriting Java In Scala
Rewriting Java In Scala
Skills Matter
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
Michael Stal
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
climatewarrior
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Scala Quick Introduction
Scala Quick Introduction
Damian Jureczko
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
Ad

Recently uploaded (20)

Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
Lessons Learned from Developing Secure AI Workflows.pdf
Lessons Learned from Developing Secure AI Workflows.pdf
Priyanka Aash
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
AI vs Human Writing: Can You Tell the Difference?
AI vs Human Writing: Can You Tell the Difference?
Shashi Sathyanarayana, Ph.D
 
Techniques for Automatic Device Identification and Network Assignment.pdf
Techniques for Automatic Device Identification and Network Assignment.pdf
Priyanka Aash
 
You are not excused! How to avoid security blind spots on the way to production
You are not excused! How to avoid security blind spots on the way to production
Michele Leroux Bustamante
 
Securing Account Lifecycles in the Age of Deepfakes.pptx
Securing Account Lifecycles in the Age of Deepfakes.pptx
FIDO Alliance
 
The Future of Technology: 2025-2125 by Saikat Basu.pdf
The Future of Technology: 2025-2125 by Saikat Basu.pdf
Saikat Basu
 
Securing AI - There Is No Try, Only Do!.pdf
Securing AI - There Is No Try, Only Do!.pdf
Priyanka Aash
 
OWASP Barcelona 2025 Threat Model Library
OWASP Barcelona 2025 Threat Model Library
PetraVukmirovic
 
cnc-processing-centers-centateq-p-110-en.pdf
cnc-processing-centers-centateq-p-110-en.pdf
AmirStern2
 
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Wenn alles versagt - IBM Tape schützt, was zählt! Und besonders mit dem neust...
Josef Weingand
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
AI VIDEO MAGAZINE - June 2025 - r/aivideo
AI VIDEO MAGAZINE - June 2025 - r/aivideo
1pcity Studios, Inc
 
Daily Lesson Log MATATAG ICT TEchnology 8
Daily Lesson Log MATATAG ICT TEchnology 8
LOIDAALMAZAN3
 
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
EIS-Webinar-Engineering-Retail-Infrastructure-06-16-2025.pdf
Earley Information Science
 
"Database isolation: how we deal with hundreds of direct connections to the d...
"Database isolation: how we deal with hundreds of direct connections to the d...
Fwdays
 
UserCon Belgium: Honey, VMware increased my bill
UserCon Belgium: Honey, VMware increased my bill
stijn40
 
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
A Constitutional Quagmire - Ethical Minefields of AI, Cyber, and Privacy.pdf
Priyanka Aash
 
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
GenAI Opportunities and Challenges - Where 370 Enterprises Are Focusing Now.pdf
Priyanka Aash
 

Scala: Devnology - Learn A Language Scala

  • 1. packagenl.devnology.workshopimportjava.util._classLearnALanguage(today: Calendar) extendsDevnology{ defwelcome(participants: List[Participant]) {participants.foreach(p => println("welcome" + p)) } def facilitators() = { Facilitator("SoemirnoKartosoewito") :: Facilitator("Jan Willem Tulp") :: Nil }}
  • 2. What’s the plan?Setup development environment (Eclipse + Scalaplugin)Form pair-programming pairsExplanation of basic concepts and syntaxLabs, labs, labs...... and of course: share knowledge!
  • 3. Euh...Scala?Scala runs on JVM and .Net VMintegrates 100% with existing librarieshybrid language: both functional and OOstatically typed“everything is an object”...Immutability, Currying, Tuples, Closures, Higher Order Functions, etc....
  • 4. Scala in the enterprise
  • 5. Run Scala as...Interactive / REPL (Read Eval Print Loop): the scala command starts an interactive shellAs scriptCompiled: scalac command compiles Scala codeSee: http://www.scala-lang.org/node/166
  • 6. Variables, Values & Type Inferencevarmsg = "welcome to ..." // msg is mutablemsg += " Devnology" msg = 3 // compiler error
  • 7. Variables, Values & Type Inferencevalmsg = "welcome to ..." // msg is immutablemsg += " Devnology" // compiler errorval n : Int = 3 // explicit type declarationvalname : String = "John"
  • 8. Functionsdef min(x: Int, y: Int) = if (x < y) x else y// equivalent:def invert(x: Int) = -x // last statement is return valuedef invert(x: Int) : Int = { return –x }Unit can be considered as java’s voidWatch out!def invert(x: Int) { // will return Unit, = is absent -x}
  • 9. Every operation is a function call1 + 2 is the same as1.+(2)“to” is not a keyword: for (i <- 0 to 10) print(i)map containsKey ‘a’ is the same as map.containsKey(‘a’)
  • 10. Listsvalscores = List(1, 2, 3) // immutablevalextraScores: List[Int] = 4 :: 5 :: 6 :: Nil// allScores = List(1, 2, 3, 4, 5, 6)// scores = List(1, 2, 3)// extraScores = List(4, 5, 6)valallScores = scores ::: extraScoresvalevenMoreScores = 7 :: allScoresNil is synonym for empty list
  • 11. Foreachvalscores = List(1, 2, 3)// equivalentscores.foreach((n: Int) => println(n))scores.foreach(n => println(n))scores.foreach(println)
  • 12. For comprehensionsvalscores = List(1, 2, 3)for (s <- scores)println(s)for (s <- scores if s > 1)println(s)
  • 13. Arraysvalnames = Array("John", "Jane")names(0) = "Richard" // Arrays are mutableval cities = new Array[String](2)cities(0) = "Amsterdam"cities(1) = "Rotterdam"for (i <- 0 to 1)println(cities(i))
  • 14. Mapsvaltowns = Map("John" -> "Amsterdam", "Jane" -> "Rotterdam") // default immutable Mapvar a = towns("John") // returns "Amsterdam"a = towns get "John”// returns Some(Amsterdam)a = towns get "John"get // returns "Amsterdam"var r = towns("Bill") // throws NoSuchElementExceptionr = towns get "Bill”// returns Nonetowns.update("John", "Delft") // returns a new Map
  • 15. Classes & Constructorsclass Person(name: String, age: Int) {if (age < 0) thrownewIllegalArgumentExceptiondefsayHello() { println("Hello, " + name) }}class Person(name: String, age: Int) {require (age >= 0)defsayHello() { println("Hello, " + name) }}
  • 16. Classes & Constructorsclass Person(name: String, age: Int) {def this(name: String) = this(name, 21) // auxiliarydef this(age: Int) = this(“John”, age) // auxiliarydef this() = this(“John”, 21) // auxiliary}
  • 17. Classes & Constructorsclass Person(name: String, age: Int)...val p = new Person("John", 33)val a = p.age// compiler errorp.name = "Richard" // compiler errorclass Person(var name: String, val age: Int)
  • 18. Companion Objects// must be declared in same file as Person classobject Person {defprintName = println("John")}valp = Person // Singleton is also an objectPerson.printName// similar to static methods in Java/C#
  • 19. Traitstrait Student {varage = 10; def greet() = {"Hello teacher!" } def study(): String // abstract method}
  • 20. Extending Traitsclass FirstGrader extends Student { override def greet() = {"Hello amazing teacher!" } override def study(): String = {“I am studying really hard!" }}
  • 21. Trait Mixin// compiler error: abstract function study from trait Student is not implementedvaljohn = new Person with StudenttraitSimpleStudent {def greet() = "Hello amazing teacher!"}// this is okval john = new Person withSimpleStudentprintln(john.greet())
  • 22. Scala Applicationobject Person def main(args: Array[String]) { // define a main method for (arg <- args)println("Hello " + arg) }}// or extend Application traitobject Person extends Application { for (name <- List("John", "Jane")) println("Hello " + name)}
  • 23. Pattern Matchingvalcolor = if (args.length > 0) args(0) else ""valfruit match {case"red"=>"apple"case"orange" =>"orange"case"yellow" =>"banana"case_ => "yuk!"}
  • 24. Case Classescase class Var(name: String) extendsExprval v = Var("sum")adds a Factory method with the name of the classall parameters implicitly get a val prefix, so they are maintained as fields“natural” implementation of toString, hashCode and equalsbig advantage: support pattern matching
  • 25. Exceptionstry {args(0).toFloat} catch { case ex: NumberFormatException => println("Oops!")}
  • 26. Tuplesvalpair = ("John", 28) // Tuple2[String, Int]println(pair._1)println(pair._2)def divProd(x: Int, y:Int) = (x / y, x * y)valdp = divProd(10, 2)println(pair._1) // 5println(pair._2) // 20