24-Oct-15 Java to Scala. Types Primitives char byte short int long float double boolean Objects String … and many more … Objects Char Byte Short Int Long.

Slides:



Advertisements
Similar presentations
Lecture 9: More on objects, classes, strings discuss hw3 assign hw4 default values for variables scope of variables and shadowing null reference and NullPointerException.
Advertisements

Generic programming in Java
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
Primitive Data Types There are a number of common objects we encounter and are treated specially by almost any programming language These are called basic.
CS16 Week 2 Part 2 Kyle Dewey. Overview Type coercion and casting More on assignment Pre/post increment/decrement scanf Constants Math library Errors.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
Introducing the Erlang Language Why Erlang?  Exemplifies the “you can have code and concurrency that is free from side effects…there is no other way”
Programming in Scala Chapter 1. Scala: both object-oriented and functional Scala blends –object-oriented and –functional programming in a –statically.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
While Loops and Do Loops. Suppose you wanted to repeat the same code over and over again? System.out.println(“text”); System.out.println(“text”); System.out.println(“text”);
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
1-Sep-15 Scala Apologia. 2 Java What’s wrong with Java? Not designed for highly concurrent programs The original Thread model was just wrong (it’s been.
JavaServer Pages Syntax Harry Richard Erwin, PhD CSE301/CIT304.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Java. Why Java? It’s the current “hot” language It’s almost entirely object-oriented It has a vast library of predefined objects It’s platform independent.
Pattern matching. The if expression The else part of an if expression is optional if ( condition ) expression1 else expression2 If the condition evaluates.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIT 590 Intro to Programming First lecture on Java.
5 BASIC CONCEPTS OF ANY PROGRAMMING LANGUAGE Let’s get started …
23-Oct-15 Abstract Data Types. 2 Data types A data type is characterized by: a set of values a data representation, which is common to all these values,
Chapter 6 Programming Languages (1) Introduction to CS 1 st Semester, 2015 Sanghyun Park.
10-Nov-15 Java Object Oriented Programming What is it?
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Selection Statements Selection Switch Conditional.
Introduction to Java Java Translation Program Structure
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Functions and Methods. Definitions and types A function is a piece of code that takes arguments and returns a result A pure function is a function whose.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
BMTRY 789 Lecture 11: Debugging Readings – Chapter 10 (3 rd Ed) from “The Little SAS Book” Lab Problems – None Homework Due – None Final Project Presentations.
Copyright Curt Hill Variables What are they? Why do we need them?
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
CS162 Week 1 Kyle Dewey. Overview Basic Introduction CS Accounts Scala survival guide.
Cases and Classes and Case Classes And Other Miscellany 16-Dec-15.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
Classes and Objects and Traits And Other Miscellany 25-Jan-16.
CPS120: Introduction to Computer Science Variables and Constants.
6-Feb-16 Scala Apologia. 2 Java What’s wrong with Java? Not designed for highly concurrent programs The original Thread model was just wrong (it’s been.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
4-Mar-16 Getting Started with Scala. Getting Scala Download ScalaIDE: / This is a customized version of Eclipse I'm.
Announcements Assignment 2 Out Today Quiz today - so I need to shut up at 4:25 1.
21-Mar-16 Getting Started with Scala. Hello World /** Everybody’s first program */ object HelloWorld { def main(args: Array[String]) { println("Hello,
Sequences and for loops. Simple for loops A for loop is used to do something with every element of a sequence scala> for (i
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
13-Jun-16 Scala Apologia. 2 Java What’s wrong with Java? Not designed for highly concurrent programs The original Thread model was just wrong (it’s been.
Information and Computer Sciences University of Hawaii, Manoa
Prof: Dr. Shu-Ching Chen TA: Samira Pouyanfar Spring 2017
Introduction to Computer Science / Procedural – 67130
Classes and Objects and Traits
Data types and variables
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Phil Tayco Slide version 1.0 Created Oct 2, 2017
Introduction to Primitive Data types
Scala Apologia 1-Jan-19.
Cases and Classes and Case Classes
Java Programming Language
Classes and Objects and Traits
Review for Midterm 3.
Introduction to Primitive Data types
CS 240 – Advanced Programming Concepts
Presentation transcript:

24-Oct-15 Java to Scala

Types Primitives char byte short int long float double boolean Objects String … and many more … Objects Char Byte Short Int Long Float Double Boolean String Function … and many more … Scala doesn't have primitives, only objects Behind the scenes, objects are converted to primitives as necessary, so there is no loss in efficiency

Type declarations int x; final int Y = 0; int[] langs = {"C++", "Java", "Scala"}; Set langs = new Set<>(); langs.add("C++"); langs.add("Java"); langs.add("Scala"); var x = 0 The keyword var introduces a mutable variable Variable declarations must include an initial value The type of variable is inferred from the initial value val y = 0 The keyword val introduces an immutable variable val langs = Array("C++", "Java", "Scala") val langs = Set("C++", "Java", "Scala")

“Statements” Scala’s “statements” should really be called “expressions,” because every statement has a value The value of many statements, for example the while loop, is () () is a value of type Unit () is the only value of type Unit () basically means “Nothing to see here. Move along.” The value of a if or match statement is the last value computed The value of a block, { … }, is the last value computed in the block A statement is ended by the end of the line (not with a semicolon) unless it is obviously incomplete, or if the next line cannot begin a valid statement For example, x = 3 * (2 * y + is obviously incomplete Because Scala lets you leave out a lot of unnecessary punctuation, sometimes a line that you think is complete really isn’t complete (or vice versa) You can end statements with semicolons, but that’s not good Scala practice 4

Constructors class Point { private double x; private double y; public Point(double x, double y) { this.x = x; this.y = y; }... } class Point(x: Double, y: Double) {... } Unqualified parameters are effectively private final instance variables

Getters Java: Make the instance variables private, and write getter methods class Point { private double x, y; public double getX() { return x; } } Point p = new Point(3.6, 4.7); System.out.println(p.getX()); Scala: Replace the primary constructor line with class Point(val x: Double, val y: Double) {...} val p = new Point(3.6, 4.7) println(p.x)

Both getters and setters Java: Write as methods public double getX() { return x; } public void setX(Double x) { this.x = x; } p.setX(2 * p.getX()); Scala: Replace the primary constructor line with class Point(var x: Double, var y: Double) p.x = 2 * p.x

Auxiliary constructors Java: Can have multiple constructors, which may or may not refer to one another public Point(double x, double y) {...} public Point() { this(0, 0); } class Point(x: Double, y: Double) {...} def this() { this(0, 0) } Every auxiliary constructor must refer to a previously defined constructor

Defining equality for public boolean equals(Object other) { if (other instanceof Point) { Point that = (Point) other; return this.x == that.x && this.y == that.y; } return false; } final override def equals(Other: Any) = { val that = other.asInstanceOf[Point] if (that == null) false else this.x == that.x && this.y == that.y OR: case class Point(x: Double, y: Double) {...}

Case classes in Scala A case class is just like a regular class, except: The methods equals, hashCode, toString, and copy are automatically defined for you, based on the parameters to the primary constructor Each of the constructor parameters becomes a var (so you have getters and setters) An apply method is created—this lets you omit the word new when creating new objects An unapply method is created, which allows you to pattern match on your objects

Input and output Scanner scanner = new Scanner(System.in); System.out.println("What is your name? "); String name = scanner.nextLine(); System.out.println("Hello, " + name); val name = readLine("What is your name? ") println("Hello, " + name)

Singleton objects class Earth { final double diameter = ; Earth earth = e; private Earth() {} public instanceOf() { if (e == null) e = new Earth(); return e; } } object Earth { val diameter = }

Operators in Scala Scala has the same arithmetic and logical operators as Java, except: ++ and -- have been removed test ? iftrue : iffalse has been replaced by if (test) iftrue else iffalse which is an expression

Familiar statement types These are the same as in Java, but have a value of ( ) : variable = expression // also +=, *=, etc. while ( condition ) { statements } do { statements } while ( condition ) These are the same as in Java, but may have a useful value: { statements } T he value of the block is the last value computed in it if ( condition ) { statements } else { statements } The value is the value of whichever block is chosen If the value is to be used, both blocks should have the same type, otherwise the type of the result is the “least upper bound” of the two types if ( condition ) { statements } The value is the value of the last statement executed, but its type is Any – if you want a value, you really should use an else As in Java, braces around a single statement may be omitted 14

The for comprehension Scala’s for is much more powerful than Java’s for Consequently, it is used much more often than the other kinds of loops We will just cover some simple cases here for (i <- 1 to 10) { println(i) } Prints the numbers 1 through 10 for (i <- 1 until 10) { println(i) } Prints the numbers 1 through 9 for (x <- 0 until myArray.length) { println(myArray(x)) } Prints all the values in myArray for (x <- myArray) { println(x) } Prints all the values in myArray for (x <- myArray if x % 2 == 0) { println(x) } Prints all the even numbers in myArray

for…yield for returns Unit, but for…yield returns a sequence of values Where possible, it returns the same type of sequence as it operates on scala> for (i <- List(1, 2, 3)) yield { 2 * i } res1: List[Int] = List(2, 4, 6) scala> for (i <- 97 to 100) yield { i.toChar } res2: scala.collection.immutable.IndexedSeq[Char] = Vector(a, b, c, d) scala> for (ch <- "abcd" if ch != 'c') yield { ch.toInt } res3: scala.collection.immutable.IndexedSeq[Int] = Vector(97, 98, 100)

Explicit pattern matching Explicit pattern matching is done with the match method: expression match { case pattern1 => expressions … case patternN => expressions }

Pattern matching Pattern matching on literal values: today match { case "Saturday" => println("Party! Party! Party!") case "Sunday" => println("Pray....") case day => println(day + " is a workday. :( ") } Pattern matching on types: something match { case x: Int => println("I'm the integer " + x) case x: String => println("I'm the String \"" + x + "\"") println("My length is " + x.length) case _ => println("I don't know what I am! :( ") }

The Option type Scala has null because it interoperates with Java; it shouldn’t be used any other time Instead, use an Option type, with values Some( value ) and None def max(list: List[Int]) = { if (list.length > 0) { val big = list reduce {(a, b) => if (a > b) a else b} Some(big) } else { None } max(myList) match { case Some(x) => println("The largest number is " + x) case None => println("There are no numbers here!!!") }

20 Java What’s wrong with Java? Not designed for highly concurrent programs The original Thread model was just wrong (it’s been fixed) Java 5+ helps by including java.util.concurrent Verbose Too much of Thing thing = new Thing(); Too much “boilerplate,” for example, getters and setters What’s right with Java? Very popular Object oriented (mostly), which is important for large projects Statically typed (more on this later) The fine large library of classes The JVM! Platform independent, highly optimized

Pet peeves Here are some things that annoy me about Java but are fixed in Scala == works for strings about 95% of the time If you write a constructor for your class, the default constructor vanishes For arrays, length is a variable; for Strings, it’s a function ArrayList strings = new ArrayList (); Special syntax for arrays (only), not for any other data structures Adding elements to a list or a map, one at a time Having to explain ++ and -- to new students By default, assert doesn’t do anything Having to write getters and setters to make my code “clean,” even when they aren’t really needed Having to create a Scanner to do simple input (for that matter, all file I/O) Checked exceptions No tuples! NullPointerException s

22 Scala is like Java, except when it isn’t Java is a good language, and Scala is a lot like it For each difference, there is a reason--none of the changes are “just to be different” Scala and Java are (almost) completely interoperable Call Java from Scala? No problem! Call Scala from Java? Some restrictions, but mostly OK. No problem— if you can supply the right type of parameters Scala compiles to.class files (a lot of them!), and can be run with either the scala command or the java command To understand Scala, it helps to understand the reasons for the changes, and what it is Scala is trying to accomplish

23 Consistency is good In Java, every value is an object--unless it’s a primitive Numbers and booleans are primitives for reasons of efficiency, so we have to treat them differently (you can’t “talk” to a primitive) In Scala, all values are objects. Period. The compiler turns them into primitives, so no efficiency is lost (behind the scenes, there are objects like RichInt ) Java has operators (+, <,...) and methods, with different syntax In Scala, operators are just methods, and in many cases you can use either syntax

24 Type safety is good, verbosity is bad Java is statically typed--a variable has a type, and can hold only values of that type You must specify the type of every variable Type errors are caught by the compiler, not at runtime--this is a big win However, it leads to a lot of typing (pun intended) Languages like Ruby and Python don’t make you declare types Easier (and more fun) to write programs Less fun to debug, especially if you have even slightly complicated types Scala is also statically typed, but it uses type inferencing--that is, it figures out the types, so you don’t have to The good news: Less typing, more fun, type errors caught by the compiler The bad news: More kinds of error messages to get familiar with

25 Verbosity Java: class Person { private String firstName; private String lastName; private int age; public Person(String firstName, String lastName, int age) { this.firstName = firstName; this.lastName = lastName; this.age = age; } public void setFirstName(String firstName) { this.firstName = firstName; } public void String getFirstName() { return this.firstName; } public void setLastName(String lastName) { this.lastName = lastName; } public void String getLastName() { return this.lastName; } public void setAge(int age) { this.age = age; } public void int getAge() { return this.age; } } Scala: class Person(var firstName: String, var lastName: String, var age: Int) Source:

26 null in Scala In Java, any method that is supposed to return an object could return null Here are your options: Always check for null Always put your method calls inside a try... catch Make sure the method can’t possibly return null Ignore the problem and depend on luck Yes, Scala has null --but only so that it can talk to Java In Scala, if a method could return “nothing,” write it to return an Option object, which is either Some( theObject ) or None This forces you to use a match statement--but only when one is really needed!

27 Uniform access In Java, myString.length () is a function, but myArray.length is a variable If age is a public field of Person, you can say: david.age = david.age + 1; but if age is accessed via methods, you would say: david.setAge(david.getAge() + 1); You have to know whether a piece of data is implemented as a variable or as a function In Scala, if age is a public field of Person, you can say: david.age = david.age + 1; but if Person defines methods age and age_=, you would say: david.age = david.age + 1; In other words, if you want to access a piece of data in Scala, you don’t have to know whether it is computed by a method or held in a simple variable This is the principle of uniform access Scala won’t let you use parentheses when you call a function with no parameters

28 Concurrency “Concurrency is the new black.” Broadly speaking, concurrency can be either: Fine-grained: Frequent interactions between threads working closely together (extremely challenging to get right) Coarse-grained: Infrequent interactions between largely independent sequential processes (much easier to get right) Java 5 and 6 provide reasonable support for traditional fine-grained concurrency Scala has total access to the Java API Hence, it can do anything Java can do And it can do much more (see next slide) Scala also has Actor s for coarse-grained concurrency

29 Scala is multiparadigm Scala is an attempt to blend object-oriented programming with functional programming Here’s the difficulty: Objects have state—that’s practically their only reason for being Functional programs are stateless Scala tries to bridge this gap Functions in Scala are first-class objects Scala encourages immutable objects All the usual functional programming functions— map, filter, fold, etc.—are available in Scala

30 Functional languages The best-known functional languages are ML, OCaml, and Haskell Functional languages are regarded as: “Ivory tower languages,” used only by academics (mostly but not entirely true) Difficult to learn (mostly true) The solution to all concurrent programming problems everywhere (exaggerated, but not entirely wrong) Scala is an “impure” functional language--you can program functionally, but it isn’t forced upon you

31 Scala as a functional language The hope--my hope, anyway--is that Scala will let people “sneak up” on functional programming (FP), and gradually learn to use it This is how C++ introduced Object-Oriented programming Even a little bit of functional programming makes some things a lot easier Meanwhile, Scala has plenty of other attractions FP really is a different way of thinking about programming, and not easy to master......but... Most people that master it, never want to go back

“You can write a Fortran program...” There’s a old saying: “You can write a Fortran program in any language.” Some people quote this as “You can write a C program...,” but the quote is older than the C language People still say this, but I discovered recently that what they mean by it has changed (!) Old meaning: You can bring your old (Fortran) programming habits into the new language, writing exactly the same kind of program you would in Fortran, whether they make sense or not, and just totally ignore the distinctive character of the new language. New meaning: You can write a crappy program in any language. Moral: You can “write a Java program in Scala.” That’s okay at first--you have to start out with what you know, which is Java. After that, you have a choice: You can (gradually) learn “the Scala way,” or you can keep writing crappy Scala programs.

33 Genealogy Scala Java C C++ Simula Smalltalk Prolog Erlang Haskell ML Lisp functional programming syntax objects pattern matching Actors Clojure

34 The End “If I were to pick a language to use today other than Java, it would be Scala.” --James Gosling, creator of Java