SlideShare ist ein Scribd-Unternehmen logo
1 von 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”);

Weitere ähnliche Inhalte

Was ist angesagt?

Scala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosScala at GenevaJUG by Iulian Dragos
Scala at GenevaJUG by Iulian DragosGenevaJUG
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
 
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...Sanjeev_Knoldus
 
1.2 Scala Basics
1.2 Scala Basics1.2 Scala Basics
1.2 Scala Basicsretronym
 
2.1 Recap From Day One
2.1 Recap From Day One2.1 Recap From Day One
2.1 Recap From Day Oneretronym
 
Scala introduction
Scala introductionScala introduction
Scala introductionvito jeng
 
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 streamRuslan Shevchenko
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Developmentvito jeng
 
Scala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesScala Back to Basics: Type Classes
Scala Back to Basics: Type ClassesTomer Gabel
 
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 jvmIsaias Barroso
 
Intro to Functional Programming in Scala
Intro to Functional Programming in ScalaIntro to Functional Programming in Scala
Intro to Functional Programming in ScalaShai Yallin
 
Scala for ruby programmers
Scala for ruby programmersScala for ruby programmers
Scala for ruby programmerstymon Tobolski
 

Was ist angesagt? (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
 

Ähnlich wie 1.2 scala basics

1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basicswpgreenway
 
2.1 recap from-day_one
2.1 recap from-day_one2.1 recap from-day_one
2.1 recap from-day_onefuturespective
 
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?Jesper Kamstrup Linnet
 
(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
 
Getting Started With Scala
Getting Started With ScalaGetting Started With Scala
Getting Started With ScalaMeetu Maltiar
 
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 developersMatthew Farwell
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Languageleague
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to ScalaBrian Hsu
 

Ähnlich wie 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
 

Mehr von futurespective

Mehr von 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
 

Kürzlich hochgeladen

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 organizationRadu Cotescu
 
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 2024The Digital Insurer
 
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 productivityPrincipled Technologies
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
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...Martijn de Jong
 
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 MenDelhi Call girls
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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 2024Rafal Los
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
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 WorkerThousandEyes
 
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 Processorsdebabhi2
 
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...Neo4j
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
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 Nanonetsnaman860154
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfhans926745
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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.pdfsudhanshuwaghmare1
 

Kürzlich hochgeladen (20)

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
 
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
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
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...
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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 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
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
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
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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
 

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