SlideShare a Scribd company logo
1 of 28
packagenl.devnology.workshop importjava.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 pairs Explanation of basic concepts and syntax Labs, labs, labs... ... and of course: share knowledge!
Euh...Scala? Scala runs on JVM and .Net VM integrates 100% with existing libraries hybrid language: both functional and OO statically 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 shell As script Compiled: scalac command compiles Scala code See: http://www.scala-lang.org/node/166
Variables, Values & Type Inference varmsg = "welcome to ..." // msg is mutable msg += " Devnology"  msg = 3 // compiler error
Variables, Values & Type Inference valmsg = "welcome to ..." // msg is immutable msg += " Devnology" // compiler error val n : Int = 3 // explicit type declaration valname : String = "John"
Functions def min(x: Int, y: Int) = if (x < y) x else y // equivalent: def invert(x: Int) = -x // last statement is return value def invert(x: Int) : Int = { return –x } Unit can be considered as java’s void Watch out! def invert(x: Int) { // will return Unit, = is absent   -x }
Every operation is a function call 1 + 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’)
Lists valscores = List(1, 2, 3) // immutable valextraScores: 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 ::: extraScores valevenMoreScores = 7 :: allScores Nil is synonym for empty list
Foreach valscores = List(1, 2, 3) // equivalent scores.foreach((n: Int) => println(n)) scores.foreach(n => println(n)) scores.foreach(println)
For comprehensions valscores = List(1, 2, 3) for (s <- scores) println(s) for (s <- scores if s > 1) println(s)
Arrays valnames = Array("John", "Jane") names(0) = "Richard" // Arrays are mutable val cities = new Array[String](2) cities(0) = "Amsterdam" cities(1) = "Rotterdam" for (i <- 0 to 1) println(cities(i))
Maps valtowns = Map("John" -> "Amsterdam", "Jane" -> "Rotterdam") // default immutable Map var a = towns("John") // returns "Amsterdam" a = towns get "John”// returns Some(Amsterdam) a = towns get "John"get // returns "Amsterdam" var r = towns("Bill") // throws NoSuchElementException r = towns get "Bill”// returns None towns.update("John", "Delft") // returns a new Map
Classes & Constructors class Person(name: String, age: Int) { if (age < 0) thrownewIllegalArgumentException defsayHello() { println("Hello, " + name) } } class Person(name: String, age: Int) { require (age >= 0) defsayHello() { println("Hello, " + name) } }
Classes & Constructors class Person(name: String, age: Int) { def this(name: String) = this(name, 21) // auxiliary def this(age: Int) = this(“John”, age) // auxiliary def this() = this(“John”, 21) // auxiliary }
Classes & Constructors class Person(name: String, age: Int) ... val p = new Person("John", 33) val a = p.age// compiler error p.name = "Richard" // compiler error class Person(var name: String, val age: Int)
Companion Objects // must be declared in same file as Person class object Person { defprintName = println("John") } valp = Person // Singleton is also an object Person.printName// similar to static methods in Java/C#
Traits trait Student { varage = 10;   def greet() = { "Hello teacher!"   }   def study(): String // abstract method }
Extending Traits class 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 implemented valjohn = new Person with Student traitSimpleStudent { def greet() = "Hello amazing teacher!" } // this is ok val john = new Person withSimpleStudent println(john.greet())
Scala Application object Person   def main(args: Array[String]) { // define a main method     for (arg <- args) println("Hello " + arg)   } } // or extend Application trait object Person extends Application {    for (name <- List("John", "Jane"))  println("Hello " + name) }
Pattern Matching valcolor = if (args.length > 0) args(0) else "" valfruit match { case"red"=>"apple" case"orange" =>"orange" case"yellow" =>"banana" case_ => "yuk!" }
Case Classes case class Var(name: String) extendsExpr val v = Var("sum") adds a Factory method with the name of the class all parameters implicitly get a val prefix, so they are maintained as fields “natural” implementation of toString, hashCode and equals big advantage: support pattern matching
Exceptions try { args(0).toFloat } catch {   case ex: NumberFormatException => println("Oops!") }
Tuples valpair = ("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) // 5 println(pair._2) // 20
LABS!! Resources: http://www.scala-lang.org/api http://scala-tools.org/scaladocs/scala-library/2.7.1/ http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees http://blogs.sun.com/sundararajan/entry/scala_for_java_programmers
THANK YOU!

More Related Content

What's hot

Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
John De Goes
 

What's hot (20)

Scala Intro
Scala IntroScala Intro
Scala Intro
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’PhinneyAnonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
Anonymous Functions in PHP 5.3 - Matthew Weier O’Phinney
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Demystifying functional programming with Scala
Demystifying functional programming with ScalaDemystifying functional programming with Scala
Demystifying functional programming with Scala
 
PHP Functions & Arrays
PHP Functions & ArraysPHP Functions & Arrays
PHP Functions & Arrays
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 
Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)Object-Oriented Programming with PHP (part 1)
Object-Oriented Programming with PHP (part 1)
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
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...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...
 
First-Class Patterns
First-Class PatternsFirst-Class Patterns
First-Class Patterns
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Introduction in php part 2
Introduction in php part 2Introduction in php part 2
Introduction in php part 2
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
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...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...
 
Sorting arrays in PHP
Sorting arrays in PHPSorting arrays in PHP
Sorting arrays in PHP
 
Being functional in PHP
Being functional in PHPBeing functional in PHP
Being functional in PHP
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 

Viewers also liked

Viewers also liked (6)

Cercapaz compendio de_oientaciones para la paz
Cercapaz compendio de_oientaciones para la pazCercapaz compendio de_oientaciones para la paz
Cercapaz compendio de_oientaciones para la paz
 
Handboek KVO
Handboek KVOHandboek KVO
Handboek KVO
 
Great marketing can save the world
Great marketing can save the worldGreat marketing can save the world
Great marketing can save the world
 
(a hopefully fairly painless introduction to) Linked Open Data
(a hopefully fairly painless introduction to) Linked Open Data(a hopefully fairly painless introduction to) Linked Open Data
(a hopefully fairly painless introduction to) Linked Open Data
 
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
Onderzoek onderpresteren 'motiveren leidt tot beter presteren'
 
Eindverslag stage Wellness Center Maassluis
Eindverslag stage Wellness Center MaassluisEindverslag stage Wellness Center Maassluis
Eindverslag stage Wellness Center Maassluis
 

Similar to Scala: Devnology - Learn A Language Scala

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
Loïc Descotte
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
Ayush Mishra
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 

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

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala - brief intro
Scala - brief introScala - brief intro
Scala - brief intro
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Scala Quick Introduction
Scala Quick IntroductionScala Quick Introduction
Scala Quick Introduction
 
Knolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in ScalaKnolx Session : Built-In Control Structures in Scala
Knolx Session : Built-In Control Structures in Scala
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 

Recently uploaded

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Decarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational PerformanceDecarbonising Commercial Real Estate: The Role of Operational Performance
Decarbonising Commercial Real Estate: The Role of Operational Performance
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
WSO2 Micro Integrator for Enterprise Integration in a Decentralized, Microser...
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on ThanabotsContinuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
Continuing Bonds Through AI: A Hermeneutic Reflection on Thanabots
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Choreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software EngineeringChoreo: Empowering the Future of Enterprise Software Engineering
Choreo: Empowering the Future of Enterprise Software Engineering
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Quantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation ComputingQuantum Leap in Next-Generation Computing
Quantum Leap in Next-Generation Computing
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 

Scala: Devnology - Learn A Language Scala

  • 1. packagenl.devnology.workshop importjava.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 pairs Explanation of basic concepts and syntax Labs, labs, labs... ... and of course: share knowledge!
  • 3. Euh...Scala? Scala runs on JVM and .Net VM integrates 100% with existing libraries hybrid language: both functional and OO statically 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 shell As script Compiled: scalac command compiles Scala code See: http://www.scala-lang.org/node/166
  • 6. Variables, Values & Type Inference varmsg = "welcome to ..." // msg is mutable msg += " Devnology" msg = 3 // compiler error
  • 7. Variables, Values & Type Inference valmsg = "welcome to ..." // msg is immutable msg += " Devnology" // compiler error val n : Int = 3 // explicit type declaration valname : String = "John"
  • 8. Functions def min(x: Int, y: Int) = if (x < y) x else y // equivalent: def invert(x: Int) = -x // last statement is return value def invert(x: Int) : Int = { return –x } Unit can be considered as java’s void Watch out! def invert(x: Int) { // will return Unit, = is absent -x }
  • 9. Every operation is a function call 1 + 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. Lists valscores = List(1, 2, 3) // immutable valextraScores: 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 ::: extraScores valevenMoreScores = 7 :: allScores Nil is synonym for empty list
  • 11. Foreach valscores = List(1, 2, 3) // equivalent scores.foreach((n: Int) => println(n)) scores.foreach(n => println(n)) scores.foreach(println)
  • 12. For comprehensions valscores = List(1, 2, 3) for (s <- scores) println(s) for (s <- scores if s > 1) println(s)
  • 13. Arrays valnames = Array("John", "Jane") names(0) = "Richard" // Arrays are mutable val cities = new Array[String](2) cities(0) = "Amsterdam" cities(1) = "Rotterdam" for (i <- 0 to 1) println(cities(i))
  • 14. Maps valtowns = Map("John" -> "Amsterdam", "Jane" -> "Rotterdam") // default immutable Map var a = towns("John") // returns "Amsterdam" a = towns get "John”// returns Some(Amsterdam) a = towns get "John"get // returns "Amsterdam" var r = towns("Bill") // throws NoSuchElementException r = towns get "Bill”// returns None towns.update("John", "Delft") // returns a new Map
  • 15. Classes & Constructors class Person(name: String, age: Int) { if (age < 0) thrownewIllegalArgumentException defsayHello() { println("Hello, " + name) } } class Person(name: String, age: Int) { require (age >= 0) defsayHello() { println("Hello, " + name) } }
  • 16. Classes & Constructors class Person(name: String, age: Int) { def this(name: String) = this(name, 21) // auxiliary def this(age: Int) = this(“John”, age) // auxiliary def this() = this(“John”, 21) // auxiliary }
  • 17. Classes & Constructors class Person(name: String, age: Int) ... val p = new Person("John", 33) val a = p.age// compiler error p.name = "Richard" // compiler error class Person(var name: String, val age: Int)
  • 18. Companion Objects // must be declared in same file as Person class object Person { defprintName = println("John") } valp = Person // Singleton is also an object Person.printName// similar to static methods in Java/C#
  • 19. Traits trait Student { varage = 10; def greet() = { "Hello teacher!" } def study(): String // abstract method }
  • 20. Extending Traits class 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 implemented valjohn = new Person with Student traitSimpleStudent { def greet() = "Hello amazing teacher!" } // this is ok val john = new Person withSimpleStudent println(john.greet())
  • 22. Scala Application object Person def main(args: Array[String]) { // define a main method for (arg <- args) println("Hello " + arg) } } // or extend Application trait object Person extends Application { for (name <- List("John", "Jane")) println("Hello " + name) }
  • 23. Pattern Matching valcolor = if (args.length > 0) args(0) else "" valfruit match { case"red"=>"apple" case"orange" =>"orange" case"yellow" =>"banana" case_ => "yuk!" }
  • 24. Case Classes case class Var(name: String) extendsExpr val v = Var("sum") adds a Factory method with the name of the class all parameters implicitly get a val prefix, so they are maintained as fields “natural” implementation of toString, hashCode and equals big advantage: support pattern matching
  • 25. Exceptions try { args(0).toFloat } catch { case ex: NumberFormatException => println("Oops!") }
  • 26. Tuples valpair = ("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) // 5 println(pair._2) // 20
  • 27. LABS!! Resources: http://www.scala-lang.org/api http://scala-tools.org/scaladocs/scala-library/2.7.1/ http://www.codecommit.com/blog/scala/roundup-scala-for-java-refugees http://blogs.sun.com/sundararajan/entry/scala_for_java_programmers