SlideShare uma empresa Scribd logo
1 de 54
Baixar para ler offline
- en bedre Java?

            Jesper Kamstrup Linnet
            jesper@linnet-data.dk

            Community Day 2010
            27. maj 2010
Om mig

•Freelancekonsulent
• Java- og .NET-udvikler/arkitekt
• Sprogbegejstret
Agenda

•Hvad er Scala?
• En bedre Java?
• Ready for prime time?
Er Java dødt som sprog?




                     Kilde: InfoQ.com
Hvis Java var en bil...
Hvad er Scala?
Kort om Scalas historie


• Startet i 2001
• Skabt af Martin Odersky
Kendetegn

•Statisk typet
• Hybridsprog
• Skalabilitet i højsædet
Java-kompatibelt

• Eksisterende Java API’er
• Afvikles på JVM’en
• Genererer .class-filer
Hvis Scala var en bil...
Hybridsprog

         =
 Objektorienteret
         +
Funktionsorienteret
Objektorienteret



1.to(5)        Range(1, 2, 3, 4, 5)
Funktionsorienteret


          val a = 10



   val f = (x: Int) => x + 5
Immutability

• Centralt i funktionsprogrammering
• Vigtigt for parallelisering
• Letter kodelæsning
Hvad gør Scala mere
     effektivt?
Syntaktisk sukker




               Image: Suat Eman / FreeDigitalPhotos.net
Hello, world



println("Hello, world")
Kompakt syntaks (1)
            Java                           Scala
public class Person {
    private final String name;
                                    class Person(
    private final String address;   	 val name: String,
     public Person(String name,
                                    	 val address: String);
	   	 String address) {
         this.name = name;
         this.address = address;
     }

    public String getName() {
        return name;
    }

    public String getAddress() {
        return address;
    }
Kompakt syntaks (2)
                        Java                                Scala
                                                     case class Person(
public class Person {
	      private final String name;
	      private final String address;

	
	
      public Person(String name, String address) {
      	      this.name = name;
                                                     	 name: String,
                                                     	 address: String);
	     	      this.address = address;
	     }

	     public String getName() {
	     	      return name;
	     }

	     public String getAddress() {
	     	      return address;
	     }

	     @Override
	     public int hashCode() {
	     	      ...
	     }

	     @Override
	     public boolean equals(Object obj) {
	     	      ...
	     }

	     @Override
	     public String toString() {
	     	      ...
	     }
Kompakt syntaks (3)
class   Car {
	 var   driven = 0.0
	
	 def   drive(distance: Double) = driven += distance
	 	
	 def   milesDriven = driven * 1.6
}

...

val car = new Car
car drive 10
copy method ala                 2 .8
                                   Sc


val person = Person("Jesper", "Kbh")

val newPerson = person.copy(address = "Aarhus")

                            Person(Jesper,Aarhus)
Collections
val list = List(1,2,3)
val map = Map(
	 	 	 	 	 "Jesper" -> 39,
	 	 	 	 	 "Peter" -> 55
				)
val set = Set(1, 2, 5, 2)
val array = Array(1, 2, 3)
Hvad foretrækker du?
            Java                          Scala
List<Integer> numbers = ...        val numbers = ...

List<Integer> result =             val result =
	 new ArrayList<Integer>();        	 numbers filter isEven
for (Integer number : numbers) {
	 if (isEven(number) {
	 	 result.add(number);
	 }
}
Anonyme funktioner
val list = List(1,2,3,4)

list filter isEven                List(2, 4)



list filter { n => n % 2 == 0 }



list filter { _ % 2 == 0 }
Eksempler
val list = List(1,2,3,4)


list map (x => x * x)      List(1, 4, 9, 16)
list sum                   10
list mkString ","          1,2,3,4
list forall { _ < 5 }      true
list partition isEven      (List(2, 4),
                           List(1, 3))
Pattern matching (1)

value match {
    case 1 => println("Tal")
    case i: Int => printf("Tallet %d", i)
    case "test" => println("Streng")
    case (x, y) => printf("Et par, x=%s, y=%s", x, y)
    case _ => println("Alt andet")
}
Pattern matching (2)
                                             Lister
value match {
    case List(_, _) => println("To elementer")
    case List(1, rest @ _*) => println("1 og flere")
}
Pattern matching (3)
                             Regulære udtryk
val Danish = "Hej (.*)".r
val English = "Hi, (.*)".r

greeting match {
	 case Danish(name) => printf("Dansk: %s", name)
	 case English(name) => printf("Engelsk: %s", name)
}
Pattern matching (4)
                                 Case classes


value match {
	 case Person(_, "Kbh") => println("Københavner")
	 case _ => println("Uden for København")
}
XML (1)


val personsXml =
	 <persons>
	 	 <person name="Jesper"><age>38</age></person>
	 	 <person name="Ulla"><age>{age}</age></person>
	 </persons>
XML (2)

val persons = personsXml  "person"

val name = person  "@name"




val names = personsXml  "@name"
XML (3)


node match {
	 case <name>{name}</name> => println(name)
	 case _ => println("Andet")
}
Duck typing




“If it walks like a duck, and quacks like a
          duck, then it is a duck”
Duck typing

public class Text extends ... {
	 public void setText (String string) {


public class Button extends ... {
	 public void setText (String string) {
Duck typing m. Scala

def update(control: { def setText(text: String) }) = {
	 	 control.setText("Hello, world")
}




type ControlWithText = { def setText(text: String) }

def update(control: ControlWithText) = {
	 control.setText("Hello, world")
}
Traits (1)
                          Som interface
trait Editable {
	 def isEditable(): Boolean
}

class EditablePerson extends Editable {
	 def isEditable() = true
}
Traits (2)
                  Definition af mixin

trait Persistable {
	 val entityManager: EntityManager = ...

	 def save = {
	 	 entityManager.persist(this)
	 }
}
Traits (3)
                    Statisk brug af mixin

class Car extends Vehicle with Persistable {
	 ...
}

val car = new Car
car.save
Traits (4)
              Dynamisk brug af mixin

class Bicycle extends Vehicle {
	 ...
}

val bicycle = new Bicycle with Persistable
bicycle.save
Traits (5)
                                   Overstyring
trait LoggingCollection extends
               java.util.Collection[String] {

	   abstract override def add(e: String) = {
	   	 printf("Adding: %s", e)
	   	 super.add(e)
	   }
}

val coll = new java.util.ArrayList[String]
                      with LoggingCollection
Traits (6)
                         Eksempel: Observer
trait Subject {
  type Observer = { def receiveUpdate(subject:Any) }

  private var observers = List[Observer]()

  def addObserver(observer:Observer) =
	 	 observers ::= observer

  def notifyObservers =
	 	 observers foreach (_.receiveUpdate(this))
}
Parallelisering

•Højere abstraktionsniveau
• Aktørmodel
• Beskedudveksling
• Share-nothing
Simpel aktør

import scala.actors.Actor._

actor {
	 calculateStuff
}

// stuff in main thread
Beskedudveksling

val parrot = actor {
	 while (true) {
	 	 receive {
	 	 	 case msg =>
	 	 	 	 println("Msg: " + msg)
	 	 }
	 }
}

parrot ! "Hello, Polly"
Ready for prime time?
Scala i den virkelige
       verden
Masser af information

• http://scala-lang.org
• Bøger

• Tutorials og artikler
Hvorfor ikke Scala?

•Ny syntaks
• “Ungt” sprog
• Værktøjsunderstøttelse
Hvorfor Scala?

•Kompatibilitet med Java
• Stærkere syntaks
• I fremgang
Hvorfor Scala?
“You only fully comprehend
the awesomeness of #scala
when after weeks of being
pure scala you have to edit
some Java again...”
           James Strachan (@jstrachan)
En bedre Java?
Java         Scala




                  + ?
          J av a+
Konklusion


En bedre og mere
  effektiv Java?
Spørgsmål?
Kontakt

•   Slides: http://bit.ly/scala-cd10

• jesper@linnet-data.dk
• http://twitter.com/jesper_linnet
• http://blog.kamstrup-linnet.dk

Mais conteúdo relacionado

Mais procurados

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
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAAiman Hud
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26Bilal Ahmed
 
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
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdfHiroshi Ono
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021Jorge Vásquez
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196Mahmoud Samir Fayed
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - IntroDavid Copeland
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Jorge Vásquez
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kirill Rozov
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scalaMeetu Maltiar
 

Mais procurados (15)

Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Intro toswift1
Intro toswift1Intro toswift1
Intro toswift1
 
Alternate JVM Languages
Alternate JVM LanguagesAlternate JVM Languages
Alternate JVM Languages
 
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
 
POLITEKNIK MALAYSIA
POLITEKNIK MALAYSIAPOLITEKNIK MALAYSIA
POLITEKNIK MALAYSIA
 
CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26CS101- Introduction to Computing- Lecture 26
CS101- Introduction to Computing- Lecture 26
 
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
 
scalaliftoff2009.pdf
scalaliftoff2009.pdfscalaliftoff2009.pdf
scalaliftoff2009.pdf
 
ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021ZIO Prelude - ZIO World 2021
ZIO Prelude - ZIO World 2021
 
The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196The Ring programming language version 1.7 book - Part 39 of 196
The Ring programming language version 1.7 book - Part 39 of 196
 
Scala for Java Developers - Intro
Scala for Java Developers - IntroScala for Java Developers - Intro
Scala for Java Developers - Intro
 
Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!Be Smart, Constrain Your Types to Free Your Brain!
Be Smart, Constrain Your Types to Free Your Brain!
 
Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3Kotlin Advanced - Apalon Kotlin Sprint Part 3
Kotlin Advanced - Apalon Kotlin Sprint Part 3
 
Data structures in scala
Data structures in scalaData structures in scala
Data structures in scala
 
JS OO and Closures
JS OO and ClosuresJS OO and Closures
JS OO and Closures
 

Destaque

JD Edwards - Automate Benefits Enrollment Leveraging ESS Work Files
JD Edwards - Automate Benefits Enrollment Leveraging ESS Work FilesJD Edwards - Automate Benefits Enrollment Leveraging ESS Work Files
JD Edwards - Automate Benefits Enrollment Leveraging ESS Work FilesSmartbridge
 
SPS 2014
SPS 2014SPS 2014
SPS 2014alain2a
 
It's No Mystery... Mobile BI Will Rule in 2015
It's No Mystery... Mobile BI Will Rule in 2015It's No Mystery... Mobile BI Will Rule in 2015
It's No Mystery... Mobile BI Will Rule in 2015Smartbridge
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsLinkedIn
 

Destaque (6)

JD Edwards - Automate Benefits Enrollment Leveraging ESS Work Files
JD Edwards - Automate Benefits Enrollment Leveraging ESS Work FilesJD Edwards - Automate Benefits Enrollment Leveraging ESS Work Files
JD Edwards - Automate Benefits Enrollment Leveraging ESS Work Files
 
Acec2014 RALfieProject
Acec2014 RALfieProjectAcec2014 RALfieProject
Acec2014 RALfieProject
 
Tiiu Maarja
Tiiu MaarjaTiiu Maarja
Tiiu Maarja
 
SPS 2014
SPS 2014SPS 2014
SPS 2014
 
It's No Mystery... Mobile BI Will Rule in 2015
It's No Mystery... Mobile BI Will Rule in 2015It's No Mystery... Mobile BI Will Rule in 2015
It's No Mystery... Mobile BI Will Rule in 2015
 
Study: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving CarsStudy: The Future of VR, AR and Self-Driving Cars
Study: The Future of VR, AR and Self-Driving Cars
 

Semelhante a Scala - en bedre Java?

Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldBTI360
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
(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
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Sunghyouk Bae
 

Semelhante a Scala - en bedre Java? (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala
ScalaScala
Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop 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
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
(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?
 
Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017Kotlin @ Coupang Backend 2017
Kotlin @ Coupang Backend 2017
 

Último

Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
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...Jeffrey Haguewood
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
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 2024Victor Rentea
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
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 DevelopersWSO2
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistandanishmna97
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Zilliz
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 

Último (20)

Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
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...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
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
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Scala - en bedre Java?

  • 1. - en bedre Java? Jesper Kamstrup Linnet jesper@linnet-data.dk Community Day 2010 27. maj 2010
  • 2. Om mig •Freelancekonsulent • Java- og .NET-udvikler/arkitekt • Sprogbegejstret
  • 3. Agenda •Hvad er Scala? • En bedre Java? • Ready for prime time?
  • 4. Er Java dødt som sprog? Kilde: InfoQ.com
  • 5. Hvis Java var en bil...
  • 7. Kort om Scalas historie • Startet i 2001 • Skabt af Martin Odersky
  • 9. Java-kompatibelt • Eksisterende Java API’er • Afvikles på JVM’en • Genererer .class-filer
  • 10. Hvis Scala var en bil...
  • 11. Hybridsprog = Objektorienteret + Funktionsorienteret
  • 12. Objektorienteret 1.to(5) Range(1, 2, 3, 4, 5)
  • 13. Funktionsorienteret val a = 10 val f = (x: Int) => x + 5
  • 14. Immutability • Centralt i funktionsprogrammering • Vigtigt for parallelisering • Letter kodelæsning
  • 15. Hvad gør Scala mere effektivt?
  • 16. Syntaktisk sukker Image: Suat Eman / FreeDigitalPhotos.net
  • 18. Kompakt syntaks (1) Java Scala public class Person { private final String name; class Person( private final String address; val name: String, public Person(String name, val address: String); String address) { this.name = name; this.address = address; } public String getName() { return name; } public String getAddress() { return address; }
  • 19. Kompakt syntaks (2) Java Scala case class Person( public class Person { private final String name; private final String address; public Person(String name, String address) { this.name = name; name: String, address: String); this.address = address; } public String getName() { return name; } public String getAddress() { return address; } @Override public int hashCode() { ... } @Override public boolean equals(Object obj) { ... } @Override public String toString() { ... }
  • 20. Kompakt syntaks (3) class Car { var driven = 0.0 def drive(distance: Double) = driven += distance def milesDriven = driven * 1.6 } ... val car = new Car car drive 10
  • 21. copy method ala 2 .8 Sc val person = Person("Jesper", "Kbh") val newPerson = person.copy(address = "Aarhus") Person(Jesper,Aarhus)
  • 22. Collections val list = List(1,2,3) val map = Map( "Jesper" -> 39, "Peter" -> 55 ) val set = Set(1, 2, 5, 2) val array = Array(1, 2, 3)
  • 23. Hvad foretrækker du? Java Scala List<Integer> numbers = ... val numbers = ... List<Integer> result = val result = new ArrayList<Integer>(); numbers filter isEven for (Integer number : numbers) { if (isEven(number) { result.add(number); } }
  • 24. Anonyme funktioner val list = List(1,2,3,4) list filter isEven List(2, 4) list filter { n => n % 2 == 0 } list filter { _ % 2 == 0 }
  • 25. Eksempler val list = List(1,2,3,4) list map (x => x * x) List(1, 4, 9, 16) list sum 10 list mkString "," 1,2,3,4 list forall { _ < 5 } true list partition isEven (List(2, 4), List(1, 3))
  • 26. Pattern matching (1) value match { case 1 => println("Tal") case i: Int => printf("Tallet %d", i) case "test" => println("Streng") case (x, y) => printf("Et par, x=%s, y=%s", x, y) case _ => println("Alt andet") }
  • 27. Pattern matching (2) Lister value match { case List(_, _) => println("To elementer") case List(1, rest @ _*) => println("1 og flere") }
  • 28. Pattern matching (3) Regulære udtryk val Danish = "Hej (.*)".r val English = "Hi, (.*)".r greeting match { case Danish(name) => printf("Dansk: %s", name) case English(name) => printf("Engelsk: %s", name) }
  • 29. Pattern matching (4) Case classes value match { case Person(_, "Kbh") => println("Københavner") case _ => println("Uden for København") }
  • 30. XML (1) val personsXml = <persons> <person name="Jesper"><age>38</age></person> <person name="Ulla"><age>{age}</age></person> </persons>
  • 31. XML (2) val persons = personsXml "person" val name = person "@name" val names = personsXml "@name"
  • 32. XML (3) node match { case <name>{name}</name> => println(name) case _ => println("Andet") }
  • 33. Duck typing “If it walks like a duck, and quacks like a duck, then it is a duck”
  • 34. Duck typing public class Text extends ... { public void setText (String string) { public class Button extends ... { public void setText (String string) {
  • 35. Duck typing m. Scala def update(control: { def setText(text: String) }) = { control.setText("Hello, world") } type ControlWithText = { def setText(text: String) } def update(control: ControlWithText) = { control.setText("Hello, world") }
  • 36. Traits (1) Som interface trait Editable { def isEditable(): Boolean } class EditablePerson extends Editable { def isEditable() = true }
  • 37. Traits (2) Definition af mixin trait Persistable { val entityManager: EntityManager = ... def save = { entityManager.persist(this) } }
  • 38. Traits (3) Statisk brug af mixin class Car extends Vehicle with Persistable { ... } val car = new Car car.save
  • 39. Traits (4) Dynamisk brug af mixin class Bicycle extends Vehicle { ... } val bicycle = new Bicycle with Persistable bicycle.save
  • 40. Traits (5) Overstyring trait LoggingCollection extends java.util.Collection[String] { abstract override def add(e: String) = { printf("Adding: %s", e) super.add(e) } } val coll = new java.util.ArrayList[String] with LoggingCollection
  • 41. Traits (6) Eksempel: Observer trait Subject { type Observer = { def receiveUpdate(subject:Any) } private var observers = List[Observer]() def addObserver(observer:Observer) = observers ::= observer def notifyObservers = observers foreach (_.receiveUpdate(this)) }
  • 43. Simpel aktør import scala.actors.Actor._ actor { calculateStuff } // stuff in main thread
  • 44. Beskedudveksling val parrot = actor { while (true) { receive { case msg => println("Msg: " + msg) } } } parrot ! "Hello, Polly"
  • 46. Scala i den virkelige verden
  • 47. Masser af information • http://scala-lang.org • Bøger • Tutorials og artikler
  • 48. Hvorfor ikke Scala? •Ny syntaks • “Ungt” sprog • Værktøjsunderstøttelse
  • 49. Hvorfor Scala? •Kompatibilitet med Java • Stærkere syntaks • I fremgang
  • 50. Hvorfor Scala? “You only fully comprehend the awesomeness of #scala when after weeks of being pure scala you have to edit some Java again...” James Strachan (@jstrachan)
  • 51. En bedre Java? Java Scala + ? J av a+
  • 52. Konklusion En bedre og mere effektiv Java?
  • 54. Kontakt • Slides: http://bit.ly/scala-cd10 • jesper@linnet-data.dk • http://twitter.com/jesper_linnet • http://blog.kamstrup-linnet.dk