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",
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 (20)

PDF
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
PPTX
Scala on Android
Jakub Kahovec
 
PDF
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
ODP
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
ODP
1.2 Scala Basics
retronym
 
ODP
2.1 Recap From Day One
retronym
 
PDF
Scala 2013 review
Sagie Davidovich
 
PDF
Scala introduction
vito jeng
 
PDF
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ruslan Shevchenko
 
PDF
A bit about Scala
Vladimir Parfinenko
 
PDF
Getting Started With Scala
Xebia IT Architects
 
ODP
JavaScript Web Development
vito jeng
 
PPTX
Scala Back to Basics: Type Classes
Tomer Gabel
 
PPT
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
PDF
Scala in Places API
Łukasz Bałamut
 
PPTX
Intro to Functional Programming in Scala
Shai Yallin
 
PPTX
Scala for curious
Tim (dev-tim) Zadorozhniy
 
PPTX
All about scala
Yardena Meymann
 
PDF
Scala for Jedi
Vladimir Parfinenko
 
KEY
Scala for ruby programmers
tymon Tobolski
 
Scala at GenevaJUG by Iulian Dragos
GenevaJUG
 
Scala on Android
Jakub Kahovec
 
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
1.2 Scala Basics
retronym
 
2.1 Recap From Day One
retronym
 
Scala 2013 review
Sagie Davidovich
 
Scala introduction
vito jeng
 
JDays Lviv 2014: Java8 vs Scala: Difference points & innovation stream
Ruslan Shevchenko
 
A bit about Scala
Vladimir Parfinenko
 
Getting Started With Scala
Xebia IT Architects
 
JavaScript Web Development
vito jeng
 
Scala Back to Basics: Type Classes
Tomer Gabel
 
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
Scala in Places API
Łukasz Bałamut
 
Intro to Functional Programming in Scala
Shai Yallin
 
Scala for curious
Tim (dev-tim) Zadorozhniy
 
All about scala
Yardena Meymann
 
Scala for Jedi
Vladimir Parfinenko
 
Scala for ruby programmers
tymon Tobolski
 

Similar to 1.2 scala basics (20)

ODP
1.2 scala basics
wpgreenway
 
ODP
2.1 recap from-day_one
futurespective
 
ODP
Introducing scala
Meetu Maltiar
 
PDF
Scala Bootcamp 1
Knoldus Inc.
 
PDF
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
ODP
Introduction to Scala
Lorenzo Dematté
 
PDF
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
PPTX
Scala
suraj_atreya
 
PDF
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
PDF
Getting Started With Scala
Meetu Maltiar
 
PPT
An introduction to scala
Mohsen Zainalpour
 
PPTX
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
PDF
The Scala Programming Language
league
 
PDF
ハイブリッド言語Scalaを使う
bpstudy
 
PPT
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
PDF
Scala Intro
Paolo Platter
 
PDF
Introduction to Scala
Aleksandar Prokopec
 
PDF
Introduction to Scala
Brian Hsu
 
PPT
Scala introduction
Yardena Meymann
 
PDF
Java Cheat Sheet
Saeid Zebardast
 
1.2 scala basics
wpgreenway
 
2.1 recap from-day_one
futurespective
 
Introducing scala
Meetu Maltiar
 
Scala Bootcamp 1
Knoldus Inc.
 
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Introduction to Scala
Lorenzo Dematté
 
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
Getting Started With Scala
Meetu Maltiar
 
An introduction to scala
Mohsen Zainalpour
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Matthew Farwell
 
The Scala Programming Language
league
 
ハイブリッド言語Scalaを使う
bpstudy
 
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Scala Intro
Paolo Platter
 
Introduction to Scala
Aleksandar Prokopec
 
Introduction to Scala
Brian Hsu
 
Scala introduction
Yardena Meymann
 
Java Cheat Sheet
Saeid Zebardast
 
Ad

More from futurespective (11)

ODP
2.5 the quiz-game
futurespective
 
ODP
2.4 xml support
futurespective
 
ODP
2.3 implicits
futurespective
 
ODP
2.2 higher order-functions
futurespective
 
ODP
1.7 functional programming
futurespective
 
ODP
1.6 oo traits
futurespective
 
ODP
1.5 pattern matching
futurespective
 
ODP
1.4 first class-functions
futurespective
 
ODP
1.3 tools and-repl
futurespective
 
ODP
1.1 motivation
futurespective
 
ODP
2.6 summary day-2
futurespective
 
2.5 the quiz-game
futurespective
 
2.4 xml support
futurespective
 
2.3 implicits
futurespective
 
2.2 higher order-functions
futurespective
 
1.7 functional programming
futurespective
 
1.6 oo traits
futurespective
 
1.5 pattern matching
futurespective
 
1.4 first class-functions
futurespective
 
1.3 tools and-repl
futurespective
 
1.1 motivation
futurespective
 
2.6 summary day-2
futurespective
 
Ad

Recently uploaded (20)

PPTX
Essential Content-centric Plugins for your Website
Laura Byrne
 
PDF
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
PDF
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
PDF
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
PPTX
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
PDF
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
PPTX
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
PPTX
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
PPTX
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
PDF
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
PDF
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
PPTX
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
PDF
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
PDF
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
[GDGoC FPTU] Spring 2025 Summary Slidess
minhtrietgect
 
Essential Content-centric Plugins for your Website
Laura Byrne
 
99 Bottles of Trust on the Wall — Operational Principles for Trust in Cyber C...
treyka
 
Modern Decentralized Application Architectures.pdf
Kalema Edgar
 
Transcript: Book industry state of the nation 2025 - Tech Forum 2025
BookNet Canada
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Agentforce World Tour Toronto '25 - Supercharge MuleSoft Development with Mod...
Alexandra N. Martinez
 
Automating Feature Enrichment and Station Creation in Natural Gas Utility Net...
Safe Software
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
NASA A Researcher’s Guide to International Space Station : Earth Observations
Dr. PANKAJ DHUSSA
 
Securing Model Context Protocol with Keycloak: AuthN/AuthZ for MCP Servers
Hitachi, Ltd. OSS Solution Center.
 
Mastering ODC + Okta Configuration - Chennai OSUG
HathiMaryA
 
Agentforce World Tour Toronto '25 - MCP with MuleSoft
Alexandra N. Martinez
 
🚀 Let’s Build Our First Slack Workflow! 🔧.pdf
SanjeetMishra29
 
“Squinting Vision Pipelines: Detecting and Correcting Errors in Vision Models...
Edge AI and Vision Alliance
 
Role_of_Artificial_Intelligence_in_Livestock_Extension_Services.pptx
DrRajdeepMadavi
 
Dev Dives: Accelerating agentic automation with Autopilot for Everyone
UiPathCommunity
 
“ONNX and Python to C++: State-of-the-art Graph Compilation,” a Presentation ...
Edge AI and Vision Alliance
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
[GDGoC FPTU] Spring 2025 Summary Slidess
minhtrietgect
 

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