SlideShare une entreprise Scribd logo
1  sur  23
Scala basics
;
Type definitions
Scala               Java

s: String           String s
i: Int              int i / Integer i
Variables
Scala:                       Java:

val s = “Hello World”        public final String s = “Hello World”;


var i = 1                    public int i = 1;


private var j = 3            private int j = 3;
Methods
Scala:                             Java:

def add(x: Int, y: Int): Int = {   public int add(int x, int y) {
    x+y                                return x + y;
}                                  }


def add(x: Int, y: Int) = x + y


def doSomething(text: String) {    public void doSometing(String text) {
}                                  }
Methods (2)
Scala:                         Java:

myObject.myMethod(1)           myObject.myMethod(1);
myObject myMethod(1)
myObject myMethod 1


myObject.myOtherMethod(1, 2)   myObject.myOtherMethod(1, 2);
myObject myOtherMethod(1, 2)


myObject.myMutatingMethod()    myObject.myMutatingMethod()
myObject.myMutatingMethod
myObject myMutatingMethod
Methods (3)
Scala:                         Java:

override def toString = ...    @Override
                               public String toString() {...}
Classes and constructors
Scala:                           Java:

class Person(val name: String)   public class Person {
                                     private final String name;
                                     public Person(String name) {
                                         this.name = name;
                                     }
                                     public String getName() {
                                         return name;
                                     }
                                 }
Traits (= Interface + Mixin)
Scala:                             Java:

trait Shape {                      interface Shape {
    def area: Double                   public double area();
}                                  }


class Circle extends Object with   public class Circle extends Object
   Shape                             implements Shape
No “static” in Scala
Scala:                          Java:

object PersonUtil {             public class PersonUtil {
    val AgeLimit = 18               public static final int
                                      AGE_LIMIT = 18;

    def countPersons(persons:
      List[Person]) = ...           public static int
                                      countPersons(List<Person>
}
                                           persons) {
                                        ...
                                    }
                                }
if-then-else
Scala:                    Java:

if (foo) {                if (foo) {
    ...                       ...
} else if (bar) {         } else if (bar) {
    ...                       ...
} else {                  } else {
    ...                       ...
}                         }
For-loops
Scala:                            Java:

for (i <- 0 to 3) {               for (int i = 0; i < 4; i++) {
    ...                               ...
}                                 }


for (s <- args) println(s)        for (String s : args) {
                                      System.out.println(s);
                                  }
While-loops
Scala:                 Java:

while (true) {         while (true) {
    ...                    ...
}                      }
Exceptions
Scala:                           Java:

throw new Exception(“...”)       throw new Exception(“...”)


try {                            try {
} catch {                        } catch (IOException e) {
    case e: IOException => ...       ...
} finally {                      } finally {
}                                }
Varargs
def foo(values: String*){ }     public void foo(String... values){ }


foo("bar", "baz")               foo("bar", "baz");


val arr = Array("bar", "baz")   String[] arr = new String[]{"bar",
foo(arr: _*)                      "baz"}
                                foo(arr);
(Almost) everything is an expression
val res = if (foo) x else y


val res = for (i <- 1 to 10) yield i    // List(1, ..., 10)


val res = try { x } catch { ...; y } finally { } // x or y
Collections – List
Scala:                             Java:

val numbers = List(1, 2, 3)        List<Integer> numbers =
                                     new ArrayList<Integer>();
val numbers = 1 :: 2 :: 3 :: Nil   numbers.add(1);
                                   numbers.add(2);
                                   numbers.add(3);


numbers(0)                         numbers.get(0);
=> 1                               => 1
Collections – Map
Scala:                      Java:

var m = Map(1 -> “apple”)   Map<Int, String> m =
m += 2 -> “orange”            new HashMap<Int, String>();
                            m.put(1, “apple”);
                            m.put(2, “orange”);


m(1)                        m.get(1);
=> “apple”                  => apple
Generics
Scala:             Java:

List[String]       List<String>
Tuples
Scala:                             Java:

val tuple: Tuple2[Int, String] =   Pair<Integer, String> tuple = new
                                     Pair<Integer, String>(1, “apple”)
   (1, “apple”)


val quadruple =
                                   ... yeah right... ;-)
   (2, “orange”, 0.5d, false)
Packages
Scala:                  Java:

package mypackage       package mypackage;
...                     ...
Imports
Scala:                               Java:

import java.util.{List, ArrayList}   import java.util.List
                                     import java.util.ArrayList


import java.io._                     import java.io.*


import java.sql.{Date => SDate}      ???
Nice to know
Scala:                               Java:
Console.println(“Hello”)             System.out.println(“Hello”);
println(“Hello”)

val line = Console.readLine()        BufferedReader r = new BufferedReader(new
val line = readLine()                InputStreamRead(System.in)
                                     String line = r.readLine();


error(“Bad”)                         throw new RuntimeException(“Bad”)

1+1                                  new Integer(1).toInt() + new Integer(1).toInt();
1 .+(1)

1 == new Object                      new Integer(1).equals(new Object());
1 eq new Object                      new Integer(1) == new Object();

 """Asregex""".r                    java.util.regex.Pattern.compile(“Asregex”);

Contenu connexe

Tendances

1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
retronym
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
retronym
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
Sagie Davidovich
 

Tendances (20)

Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian Dragos
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basics
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day One
 
Scala 2013 review
Scala 2013 reviewScala 2013 review
Scala 2013 review
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
JDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation streamJDays Lviv 2014:  Java8 vs Scala:  Difference points & innovation stream
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
 
A bit about Scala
A bit about ScalaA bit about Scala
A bit about Scala
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type Classes
 
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 in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in Scala
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
All about scala
All about scalaAll about scala
All about scala
 
Scala for Jedi
Scala for JediScala for Jedi
Scala for Jedi
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmers
 

Similaire à 1.2 scala basics

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
wpgreenway
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
futurespective
 
(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
 

Similaire à 1.2 scala basics (20)

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_one
 
Introducing scala
Introducing scalaIntroducing scala
Introducing scala
 
Scala Bootcamp 1
Scala Bootcamp 1Scala Bootcamp 1
Scala Bootcamp 1
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Scala
ScalaScala
Scala
 
(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?
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With Scala
 
An introduction to scala
An introduction to scalaAn introduction to scala
An introduction to scala
 
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
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 

Plus de futurespective

Plus de futurespective (11)

2.5 the quiz-game
2.5 the quiz-game2.5 the quiz-game
2.5 the quiz-game
 
2.4 xml support
2.4 xml support2.4 xml support
2.4 xml support
 
2.3 implicits
2.3 implicits2.3 implicits
2.3 implicits
 
2.2 higher order-functions
2.2 higher order-functions2.2 higher order-functions
2.2 higher order-functions
 
1.7 functional programming
1.7 functional programming1.7 functional programming
1.7 functional programming
 
1.6 oo traits
1.6 oo traits1.6 oo traits
1.6 oo traits
 
1.5 pattern matching
1.5 pattern matching1.5 pattern matching
1.5 pattern matching
 
1.4 first class-functions
1.4 first class-functions1.4 first class-functions
1.4 first class-functions
 
1.3 tools and-repl
1.3 tools and-repl1.3 tools and-repl
1.3 tools and-repl
 
1.1 motivation
1.1 motivation1.1 motivation
1.1 motivation
 
2.6 summary day-2
2.6 summary day-22.6 summary day-2
2.6 summary day-2
 

Dernier

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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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 ...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
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...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 

1.2 scala basics

  • 2. ;
  • 3. Type definitions Scala Java s: String String s i: Int int i / Integer i
  • 4. Variables Scala: Java: val s = “Hello World” public final String s = “Hello World”; var i = 1 public int i = 1; private var j = 3 private int j = 3;
  • 5. Methods Scala: Java: def add(x: Int, y: Int): Int = { public int add(int x, int y) { x+y return x + y; } } def add(x: Int, y: Int) = x + y def doSomething(text: String) { public void doSometing(String text) { } }
  • 6. Methods (2) Scala: Java: myObject.myMethod(1) myObject.myMethod(1); myObject myMethod(1) myObject myMethod 1 myObject.myOtherMethod(1, 2) myObject.myOtherMethod(1, 2); myObject myOtherMethod(1, 2) myObject.myMutatingMethod() myObject.myMutatingMethod() myObject.myMutatingMethod myObject myMutatingMethod
  • 7. Methods (3) Scala: Java: override def toString = ... @Override public String toString() {...}
  • 8. Classes and constructors Scala: Java: class Person(val name: String) public class Person { private final String name; public Person(String name) { this.name = name; } public String getName() { return name; } }
  • 9. Traits (= Interface + Mixin) Scala: Java: trait Shape { interface Shape { def area: Double public double area(); } } class Circle extends Object with public class Circle extends Object Shape implements Shape
  • 10. No “static” in Scala Scala: Java: object PersonUtil { public class PersonUtil { val AgeLimit = 18 public static final int AGE_LIMIT = 18; def countPersons(persons: List[Person]) = ... public static int countPersons(List<Person> } persons) { ... } }
  • 11. if-then-else Scala: Java: if (foo) { if (foo) { ... ... } else if (bar) { } else if (bar) { ... ... } else { } else { ... ... } }
  • 12. For-loops Scala: Java: for (i <- 0 to 3) { for (int i = 0; i < 4; i++) { ... ... } } for (s <- args) println(s) for (String s : args) { System.out.println(s); }
  • 13. While-loops Scala: Java: while (true) { while (true) { ... ... } }
  • 14. Exceptions Scala: Java: throw new Exception(“...”) throw new Exception(“...”) try { try { } catch { } catch (IOException e) { case e: IOException => ... ... } finally { } finally { } }
  • 15. Varargs def foo(values: String*){ } public void foo(String... values){ } foo("bar", "baz") foo("bar", "baz"); val arr = Array("bar", "baz") String[] arr = new String[]{"bar", foo(arr: _*) "baz"} foo(arr);
  • 16. (Almost) everything is an expression val res = if (foo) x else y val res = for (i <- 1 to 10) yield i // List(1, ..., 10) val res = try { x } catch { ...; y } finally { } // x or y
  • 17. Collections – List Scala: Java: val numbers = List(1, 2, 3) List<Integer> numbers = new ArrayList<Integer>(); val numbers = 1 :: 2 :: 3 :: Nil numbers.add(1); numbers.add(2); numbers.add(3); numbers(0) numbers.get(0); => 1 => 1
  • 18. Collections – Map Scala: Java: var m = Map(1 -> “apple”) Map<Int, String> m = m += 2 -> “orange” new HashMap<Int, String>(); m.put(1, “apple”); m.put(2, “orange”); m(1) m.get(1); => “apple” => apple
  • 19. Generics Scala: Java: List[String] List<String>
  • 20. Tuples Scala: Java: val tuple: Tuple2[Int, String] = Pair<Integer, String> tuple = new Pair<Integer, String>(1, “apple”) (1, “apple”) val quadruple = ... yeah right... ;-) (2, “orange”, 0.5d, false)
  • 21. Packages Scala: Java: package mypackage package mypackage; ... ...
  • 22. Imports Scala: Java: import java.util.{List, ArrayList} import java.util.List import java.util.ArrayList import java.io._ import java.io.* import java.sql.{Date => SDate} ???
  • 23. Nice to know Scala: Java: Console.println(“Hello”) System.out.println(“Hello”); println(“Hello”) val line = Console.readLine() BufferedReader r = new BufferedReader(new val line = readLine() InputStreamRead(System.in) String line = r.readLine(); error(“Bad”) throw new RuntimeException(“Bad”) 1+1 new Integer(1).toInt() + new Integer(1).toInt(); 1 .+(1) 1 == new Object new Integer(1).equals(new Object()); 1 eq new Object new Integer(1) == new Object(); """Asregex""".r java.util.regex.Pattern.compile(“Asregex”);