SlideShare uma empresa Scribd logo
1 de 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”);

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de futurespective

Mais 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
 

Último

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
 

Último (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
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
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
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
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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 New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 

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”);