SlideShare ist ein Scribd-Unternehmen logo
1 von 19
SCALA
An introduction
What is Scala?
• Scala is a multi-paradigm programming language based
on the JVM
• It combines Object Orientation (OO) with the principles of
Functional Programming (FP)
• Unlike Groovy, it is statically typed, although the syntax is
similar
• It’s fully interoperable with Java
• It was created by Martin Odersky in 2003, who also
brought Generics to Java.
• The name is a Portmanteau for Scalable Langauge (cute)
Scala – a brief historic view
What is Scala?
• Interoperability means:
• You can use any Java library within Java
• You can compile Scala and Java together in one project
• You can use Scala classes and objects from Java
• And coding?
• There’s a full support from the most important IDEs, such as
eclipse and IntelliJ
• Maven and Gradle have plugins for Scala
• Scala’s build tool SBT can also be for Java projects.
What is Scala?
• Interoperability means:
• You can use any Java library within Java
• You can compile Scala and Java together in one project
• You can use Scala classes and objects from Java
• And coding?
• There’s a full support from the most important IDEs, such as
eclipse and IntelliJ
• Maven and Gradle have plugins for Scala
• Scala’s build tool SBT can also be for Java projects.
Language features - classes
• Classes in Scala are basically the same as classes in
Java
• No primitives – everything is really an object, including the
scala equivalents of void (Unit), byte, short, int long etc…
• To achieve this, Scala bridges primitive value classes by
their super class AnyVal, while traditional (‘Java’) objects
are represented by their super class AnyRef, which is the
equivalent to java.lang.Object. AnyRef and AnyVal both
specialize Any.
Language features - objects
• Since “static” in Java is quite clunky and inconsistent with
the concept of pure OO, Scala introduces the concept of
objects.
• An Object in scala is a singleton instance of a transparent
class of a given type.
Companion objects are objects with
the same name as a class in the same
file. They have private access rights to
methods in the class.
A common use case for companions
are factory methods and conversions.
Language features - traits
Traits are Scala’s interface system – with some differences:
• They can be partially implemented, such as Java 8’s default
implementations in interfaces.
• They allow safe multiple inheritance while circumventing the
diamond problem (Super class A, B and C inherit from A, D inherits
from B and C) -> inheritance of overridden methods is defined by
the order of declaration, from left to right using the ‘with’ keyword.
Language features - immutability
• In contrast to Java, where members are mutable unless
otherwise specified, Scala propagates immutability by
default.
• The obvious reason for defaulting to immutability is safety
against race conditions in concurrency.
The val keyword defines immutable variables, basically like
final in Java
The var keyword defines mutable variables and should only
be used for local scope variables.
Language features - syntax
A main aspect of Scala is Inference – types are derived
from their implicit declaration.
scalac – the compiler – will deduce that foo is a String, so
there’s no need for an extra declaration. The same thing
applies to the colon. It’s optional.
Return is optional too. The last statement of a method,
defined by the def keyword is inferred.
val foo : String = „bar“;
val foo = „bar“
def do Foo(bar : String) : String = {
„foo“ + bar
}
Language features – case classes
Case classes are regular classes which export their
constructor parameters and provide support for pattern
matching.
This allow pattern matching of the sort expression match
case
case class Foo(val bar : String)
val bat = Foo(„oof“)
Bat.bar will return oof.
val bat = Foo("oof")
bat match {
case Foo("bar") => "yeah"
case Foo("oof") => "oh no"
case _ => "nope"
}
Language features - collections
Unlike Java, Scala has two different types of collections:
mutable and immutable collections. Both inherit from the
same parent trait – Traversable.
The main difference between the two is philosophical. With
immutable collections, you either recreate your collection or
work with buffers, which you convert, analogous to what
you do with StringBuilder and String in Java. Mutable
collections behave very much like their Java cousins –
Note that Buffers such as ArrayBuffer and ListBuffers are
part of the mutable collection family.
Working with Collections
The main difference between collections in Java and in
Scala is that collection manipulation is functional, similar to
the Stream API in Java 8. Instead of having to iterate
through a collection, modify and fill a new collection, scala
offers a few nifty methods:
Map:
Filter:
Collect:
val bat = List("dtag", „Xplosion", "im", "google")
bat.map( f => f.toUpperCase) // all elements in Uppercase
val bat = List("dtag", „Xplosion", "im", "google")
bat.filter( f => Character.isUpperCase(f.charAt(0)) ) // only Xplosion
val strings = bat collect { case s: String => s }
val ints = bat collect { case i: Int => i }
Working with Collections – continued..
Partition:
mkString:
flatMap:
Range:
val intList = List(2,7,9,1,6,5,8,2,4,6,2,9,8)
val (big,small) = intList partition (_ > 5)
val stringified = big map (s => s + ",") mkString
println(stringified dropRight 1) // dropRight removes the last ,
def doSomething(i:Int): Seq[Int] {Seq[Int](i, i*2}
val result = small flatMap (i => doSomething(i)} )
val range = 1 to 200 // syntcatic sugar for
val range2 = List.range(1,200)
Working with Collections – iterating..
for:
foreach:
yield:
while:
val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim")
for (name <- names) println(name)
for (name <- names if name.startsWith("J")) // comprehension
val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim")
names foreach( s => s + " Dobalina")
val results = for (name <- names) yield (name takeRight 1)
println(names) // Vector(Bob, Fred, Joe, Julia, Kim)
println(results) // Vector(b, d, e, a, m)
val reader = new DataFileReader[A](...);
val results = Seq.newBuilder[A]
while (reader.hasNext) {
results += reader.next()
}
results.result
Working with Collections – incrementing..
Mutable Collections:
Immutable Collections:
Maps:
val x = mutable.MutableList(1, 2, 3, 4, 5)
x += 6 // like list.add()
x ++= mutable.MutableList(7, 8, 9) // like list.addAll()
val y = List(1,2,3,4)
val z = 5 :: y
println(z) // yields List(5, 1, 2, 3, 4)
val zz = y ::: List(5)
println(zz) // yields List(1, 2, 3, 4, 5)
var states = scala.collection.mutable.Map("AK" -> "Alaska")
// add elements with +=
states += ("CO" -> "Colorado", “NY" -> “NYC")
states -= "KY“ // remove elements with -=
states("AK") = "Alaska, The Big State“ // update
Tail recursions
Scala has built-in support for tail recursions. An annotation
will ensure that the recursion completes.
val range = 1 to 200
def max(ints: List[Int]): Int = {
@tailrec
def maxAccum(ints: List[Int], theMax: Int): Int = {
if (ints.isEmpty) {
return theMax
} else {
val newMax = if (ints.head > theMax) ints.head else theMax
maxAccum(ints.tail, newMax)
}
}
maxAccum(ints, 0)
}
max(range toList)
Scala Options
Scala has built-in support for optional values, which
elegantly circumvents the Null-Billion-Dollar mistake.
def toInt(in: String): Option[Int] = {
try {
Some(Integer.parseInt(in.trim))
} catch {
case e: NumberFormatException => None
}
}
toInt("154564545") match {
case Some(i) => println(i)
case None => println("That didn't work.")
}
toInt("154564545").getOrElse(0)
Scala - conclusion
Scala’s advantage and at the same time draw back is it’s
syntactic sugar. If you stick to a Javaesque style, noboday
will complain.
Some concepts such as implicits, bounding and other
features are alien, but not necessary
The plus side is the incredible power of FP in a OO setting,
which isn’t far from Java shores.

Weitere ähnliche Inhalte

Was ist angesagt?

scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationMartin Odersky
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaRahul Jain
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaDerek Chen-Becker
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of ScalaMartin Odersky
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In PracticeMichiel Borkent
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsMiles Sabin
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functionaldjspiewak
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Derek Chen-Becker
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in ScalaPatrick Nicolas
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange openingMartin Odersky
 

Was ist angesagt? (19)

scala
scalascala
scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentationScala - The Simple Parts, SFScala presentation
Scala - The Simple Parts, SFScala presentation
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
Scala jargon cheatsheet
Scala jargon cheatsheetScala jargon cheatsheet
Scala jargon cheatsheet
 
The Evolution of Scala
The Evolution of ScalaThe Evolution of Scala
The Evolution of Scala
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
Functional Programming In Practice
Functional Programming In PracticeFunctional Programming In Practice
Functional Programming In Practice
 
An Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional ParadigmsAn Introduction to Scala - Blending OO and Functional Paradigms
An Introduction to Scala - Blending OO and Functional Paradigms
 
Practically Functional
Practically FunctionalPractically Functional
Practically Functional
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010Starting with Scala : Frontier Developer's Meetup December 2010
Starting with Scala : Frontier Developer's Meetup December 2010
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
Advanced Functional Programming in Scala
Advanced Functional Programming in ScalaAdvanced Functional Programming in Scala
Advanced Functional Programming in Scala
 
Scala eXchange opening
Scala eXchange openingScala eXchange opening
Scala eXchange opening
 

Ähnlich wie Scala intro for Java devs 20150324

Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersMiles Sabin
 
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 jvmIsaias Barroso
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuHavoc Pennington
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
Scala overview
Scala overviewScala overview
Scala overviewSteve Min
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 

Ähnlich wie Scala intro for Java devs 20150324 (20)

Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Intro to Scala
 Intro to Scala Intro to Scala
Intro to Scala
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
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
 
Scala
ScalaScala
Scala
 
Scala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on HerokuScala, Akka, and Play: An Introduction on Heroku
Scala, Akka, and Play: An Introduction on Heroku
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
Scala overview
Scala overviewScala overview
Scala overview
 
Scala presentationjune112011
Scala presentationjune112011Scala presentationjune112011
Scala presentationjune112011
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Scala
ScalaScala
Scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 

Kürzlich hochgeladen

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 

Kürzlich hochgeladen (20)

Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

Scala intro for Java devs 20150324

  • 2. What is Scala? • Scala is a multi-paradigm programming language based on the JVM • It combines Object Orientation (OO) with the principles of Functional Programming (FP) • Unlike Groovy, it is statically typed, although the syntax is similar • It’s fully interoperable with Java • It was created by Martin Odersky in 2003, who also brought Generics to Java. • The name is a Portmanteau for Scalable Langauge (cute)
  • 3. Scala – a brief historic view
  • 4. What is Scala? • Interoperability means: • You can use any Java library within Java • You can compile Scala and Java together in one project • You can use Scala classes and objects from Java • And coding? • There’s a full support from the most important IDEs, such as eclipse and IntelliJ • Maven and Gradle have plugins for Scala • Scala’s build tool SBT can also be for Java projects.
  • 5. What is Scala? • Interoperability means: • You can use any Java library within Java • You can compile Scala and Java together in one project • You can use Scala classes and objects from Java • And coding? • There’s a full support from the most important IDEs, such as eclipse and IntelliJ • Maven and Gradle have plugins for Scala • Scala’s build tool SBT can also be for Java projects.
  • 6. Language features - classes • Classes in Scala are basically the same as classes in Java • No primitives – everything is really an object, including the scala equivalents of void (Unit), byte, short, int long etc… • To achieve this, Scala bridges primitive value classes by their super class AnyVal, while traditional (‘Java’) objects are represented by their super class AnyRef, which is the equivalent to java.lang.Object. AnyRef and AnyVal both specialize Any.
  • 7. Language features - objects • Since “static” in Java is quite clunky and inconsistent with the concept of pure OO, Scala introduces the concept of objects. • An Object in scala is a singleton instance of a transparent class of a given type. Companion objects are objects with the same name as a class in the same file. They have private access rights to methods in the class. A common use case for companions are factory methods and conversions.
  • 8. Language features - traits Traits are Scala’s interface system – with some differences: • They can be partially implemented, such as Java 8’s default implementations in interfaces. • They allow safe multiple inheritance while circumventing the diamond problem (Super class A, B and C inherit from A, D inherits from B and C) -> inheritance of overridden methods is defined by the order of declaration, from left to right using the ‘with’ keyword.
  • 9. Language features - immutability • In contrast to Java, where members are mutable unless otherwise specified, Scala propagates immutability by default. • The obvious reason for defaulting to immutability is safety against race conditions in concurrency. The val keyword defines immutable variables, basically like final in Java The var keyword defines mutable variables and should only be used for local scope variables.
  • 10. Language features - syntax A main aspect of Scala is Inference – types are derived from their implicit declaration. scalac – the compiler – will deduce that foo is a String, so there’s no need for an extra declaration. The same thing applies to the colon. It’s optional. Return is optional too. The last statement of a method, defined by the def keyword is inferred. val foo : String = „bar“; val foo = „bar“ def do Foo(bar : String) : String = { „foo“ + bar }
  • 11. Language features – case classes Case classes are regular classes which export their constructor parameters and provide support for pattern matching. This allow pattern matching of the sort expression match case case class Foo(val bar : String) val bat = Foo(„oof“) Bat.bar will return oof. val bat = Foo("oof") bat match { case Foo("bar") => "yeah" case Foo("oof") => "oh no" case _ => "nope" }
  • 12. Language features - collections Unlike Java, Scala has two different types of collections: mutable and immutable collections. Both inherit from the same parent trait – Traversable. The main difference between the two is philosophical. With immutable collections, you either recreate your collection or work with buffers, which you convert, analogous to what you do with StringBuilder and String in Java. Mutable collections behave very much like their Java cousins – Note that Buffers such as ArrayBuffer and ListBuffers are part of the mutable collection family.
  • 13. Working with Collections The main difference between collections in Java and in Scala is that collection manipulation is functional, similar to the Stream API in Java 8. Instead of having to iterate through a collection, modify and fill a new collection, scala offers a few nifty methods: Map: Filter: Collect: val bat = List("dtag", „Xplosion", "im", "google") bat.map( f => f.toUpperCase) // all elements in Uppercase val bat = List("dtag", „Xplosion", "im", "google") bat.filter( f => Character.isUpperCase(f.charAt(0)) ) // only Xplosion val strings = bat collect { case s: String => s } val ints = bat collect { case i: Int => i }
  • 14. Working with Collections – continued.. Partition: mkString: flatMap: Range: val intList = List(2,7,9,1,6,5,8,2,4,6,2,9,8) val (big,small) = intList partition (_ > 5) val stringified = big map (s => s + ",") mkString println(stringified dropRight 1) // dropRight removes the last , def doSomething(i:Int): Seq[Int] {Seq[Int](i, i*2} val result = small flatMap (i => doSomething(i)} ) val range = 1 to 200 // syntcatic sugar for val range2 = List.range(1,200)
  • 15. Working with Collections – iterating.. for: foreach: yield: while: val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim") for (name <- names) println(name) for (name <- names if name.startsWith("J")) // comprehension val names = Vector("Bob", "Fred", "Joe", "Julia", "Kim") names foreach( s => s + " Dobalina") val results = for (name <- names) yield (name takeRight 1) println(names) // Vector(Bob, Fred, Joe, Julia, Kim) println(results) // Vector(b, d, e, a, m) val reader = new DataFileReader[A](...); val results = Seq.newBuilder[A] while (reader.hasNext) { results += reader.next() } results.result
  • 16. Working with Collections – incrementing.. Mutable Collections: Immutable Collections: Maps: val x = mutable.MutableList(1, 2, 3, 4, 5) x += 6 // like list.add() x ++= mutable.MutableList(7, 8, 9) // like list.addAll() val y = List(1,2,3,4) val z = 5 :: y println(z) // yields List(5, 1, 2, 3, 4) val zz = y ::: List(5) println(zz) // yields List(1, 2, 3, 4, 5) var states = scala.collection.mutable.Map("AK" -> "Alaska") // add elements with += states += ("CO" -> "Colorado", “NY" -> “NYC") states -= "KY“ // remove elements with -= states("AK") = "Alaska, The Big State“ // update
  • 17. Tail recursions Scala has built-in support for tail recursions. An annotation will ensure that the recursion completes. val range = 1 to 200 def max(ints: List[Int]): Int = { @tailrec def maxAccum(ints: List[Int], theMax: Int): Int = { if (ints.isEmpty) { return theMax } else { val newMax = if (ints.head > theMax) ints.head else theMax maxAccum(ints.tail, newMax) } } maxAccum(ints, 0) } max(range toList)
  • 18. Scala Options Scala has built-in support for optional values, which elegantly circumvents the Null-Billion-Dollar mistake. def toInt(in: String): Option[Int] = { try { Some(Integer.parseInt(in.trim)) } catch { case e: NumberFormatException => None } } toInt("154564545") match { case Some(i) => println(i) case None => println("That didn't work.") } toInt("154564545").getOrElse(0)
  • 19. Scala - conclusion Scala’s advantage and at the same time draw back is it’s syntactic sugar. If you stick to a Javaesque style, noboday will complain. Some concepts such as implicits, bounding and other features are alien, but not necessary The plus side is the incredible power of FP in a OO setting, which isn’t far from Java shores.