SlideShare a Scribd company logo
1 of 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”);

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

More from futurespective

More from 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
 

Recently uploaded

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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