SlideShare a Scribd company logo
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", "baz"}
foo(arr: _*)                    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

ODP
1.2 scala basics
PDF
Workshop Scala
PDF
Starting with Scala : Frontier Developer's Meetup December 2010
PPT
Scala - brief intro
PDF
Scala vs Java 8 in a Java 8 World
PDF
PDF
Stepping Up : A Brief Intro to Scala
ODP
Functional Objects & Function and Closures
1.2 scala basics
Workshop Scala
Starting with Scala : Frontier Developer's Meetup December 2010
Scala - brief intro
Scala vs Java 8 in a Java 8 World
Stepping Up : A Brief Intro to Scala
Functional Objects & Function and Closures

What's hot (20)

PDF
scala
ODP
1.2 Scala Basics
PDF
Scala at GenevaJUG by Iulian Dragos
ODP
2.1 Recap From Day One
ODP
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
PPTX
Scala on Android
PDF
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
PDF
Scaladroids: Developing Android Apps with Scala
PDF
Scala 2013 review
PDF
Scala introduction
PPTX
Scala Back to Basics: Type Classes
PDF
Getting Started With Scala
PPT
Scala uma poderosa linguagem para a jvm
PDF
A bit about Scala
PPTX
Scala for curious
ODP
JavaScript Web Development
PPTX
Intro to Functional Programming in Scala
PDF
Scala collections api expressivity and brevity upgrade from java
PPTX
Joy of scala
PDF
Scala for Jedi
scala
1.2 Scala Basics
Scala at GenevaJUG by Iulian Dragos
2.1 Recap From Day One
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala on Android
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Scaladroids: Developing Android Apps with Scala
Scala 2013 review
Scala introduction
Scala Back to Basics: Type Classes
Getting Started With Scala
Scala uma poderosa linguagem para a jvm
A bit about Scala
Scala for curious
JavaScript Web Development
Intro to Functional Programming in Scala
Scala collections api expressivity and brevity upgrade from java
Joy of scala
Scala for Jedi
Ad

Viewers also liked (9)

PPTX
Mouros galegos
ODP
1.1 motivation
PDF
What Is Compost Tea (Tagalog Version)
PPTX
SaaS (Software-as-a-Service) as-a-secure-service
PPTX
Delgro Organic Fertilizer updated 2014may26
PDF
Korean Natural Farming System
PPTX
Vermi Presentation
PPTX
Vermiculture and Vermicomposting in the Philippines
PDF
Learn BEM: CSS Naming Convention
Mouros galegos
1.1 motivation
What Is Compost Tea (Tagalog Version)
SaaS (Software-as-a-Service) as-a-secure-service
Delgro Organic Fertilizer updated 2014may26
Korean Natural Farming System
Vermi Presentation
Vermiculture and Vermicomposting in the Philippines
Learn BEM: CSS Naming Convention
Ad

Similar to 1.2 scala basics (20)

ODP
2.1 recap from-day_one
ODP
Introducing scala
PDF
Scala Bootcamp 1
ODP
Introduction to Scala
PDF
Scala - en bedre Java?
PDF
Scala - en bedre og mere effektiv Java?
PPTX
PDF
Getting Started With Scala
PPT
An introduction to scala
PDF
(How) can we benefit from adopting scala?
PPTX
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
PDF
ハイブリッド言語Scalaを使う
PDF
The Scala Programming Language
PPT
Scala in a nutshell by venkat
PDF
Scala in Places API
PDF
Introduction to Scala
PDF
Introduction to Scala
PDF
Scala Intro
PPT
Scala introduction
PDF
Java Cheat Sheet
2.1 recap from-day_one
Introducing scala
Scala Bootcamp 1
Introduction to Scala
Scala - en bedre Java?
Scala - en bedre og mere effektiv Java?
Getting Started With Scala
An introduction to scala
(How) can we benefit from adopting scala?
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
ハイブリッド言語Scalaを使う
The Scala Programming Language
Scala in a nutshell by venkat
Scala in Places API
Introduction to Scala
Introduction to Scala
Scala Intro
Scala introduction
Java Cheat Sheet

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", "baz"} foo(arr: _*) 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”);