Cases and Classes and Case Classes And Other Miscellany 16-Dec-15.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 14 Introduction to Ruby.
Advertisements

Intro to Scala Lists. Scala Lists are always immutable. This means that a list in Scala, once created, will remain the same.
More about functions Plus a few random things. 2 Tail recursion A function is said to be tail recursive if the recursive call is the very last thing it.
Local Variables and Scope Benjamin Fein. Variable Scope A variable’s scope consists of all code blocks in which it is visible. A variable is considered.
CS0007: Introduction to Computer Programming Console Output, Variables, Literals, and Introduction to Type.
Fancy Parameters. Class parameters When you define a class, you typically give it parameters scala> class Point(val x: Double, val y: Double) defined.
10-Jun-15 Just Enough Java. Variables A variable is a “box” that holds data Every variable has a name Examples: name, age, address, isMarried Variables.
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
11-Jun-15 Just Enough Java. 2 What is Java? Java is a programming language: a language that you can learn to write, and the computer can be made to understand.
Access to Names Namespaces, Scopes, Access privileges.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
18-Jun-15 Arrays. 2 A problem with simple variables One variable holds one value The value may change over time, but at any given time, a variable holds.
10 November JavaScript. Presentation Hints What do YOU think makes a good presentation Some of my suggestions Don’t write full sentences on slides Talk,
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Getting Functional. 2 What is Functional Programming (FP)? In FP, Functions are first-class objects. That is, they are values, just like other objects.
Characters and Strings. Characters In Java, a char is a primitive type that can hold one single character A character can be: –A letter or digit –A punctuation.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Methods. Why methods? A method gives a name to something that you want to do, so you don’t have to think about how to do it, you just do it The name should.
CSC 142 C 1 CSC 142 Object based programming in Java [Reading: chapter 4]
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Numeric Types, Expressions, and Output ROBERT REAVES.
Unit 3: Java Data Types Math class and String class.
Pattern matching. The if expression The else part of an if expression is optional if ( condition ) expression1 else expression2 If the condition evaluates.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
Strings The Basics. Strings can refer to a string variable as one variable or as many different components (characters) string values are delimited by.
Classes CS 21a: Introduction to Computing I First Semester,
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
Introduction to Functional Programming and ML CS 331 Principles of Programming Languages.
More about Classes and Objects. Names Scala has three kinds of names for variables and methods Names composed of letters, underscores, and dollar signs.
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.
Programming in Java Dr. M. Ahmadzadeh. Course Outline (subject to tiny changes) I will cover the following but not necessarily in this order. –Strings.
ICAPRG301A Week 2 Strings and things Charles Babbage Developed the design for the first computer which he called a difference engine, though.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Java Overview. Comments in a Java Program Comments can be single line comments like C++ Example: //This is a Java Comment Comments can be spread over.
Programming in Java CSCI-2220 Object Oriented Programming.
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
0 Odds and Ends in Haskell: Folding, I/O, and Functors Adapted from material by Miran Lipovaca.
Using Objects. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L7: Objects Slide 2 Java.
24-Dec-15 Class Structure. 2 Classes A class describes a set of objects The objects are called instances of the class A class describes: Fields (instance.
Classes and Objects and Traits And Other Miscellany 25-Jan-16.
COMP 110: Spring Announcements Lab 1 due Wednesday at Noon Assignment 1 available on website Online drop date is today.
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
17-Feb-16 String and StringBuilder Part I: String.
Getting Functional. Object-Oriented Programming in Scala Scala is object-oriented, and is based on Java’s model An object is a singleton object (there.
Methods main concepts – method call – object 's methods – actual parameters – method declaration – formal parameters – return value other concepts – method.
Variable Variables A variable variable has as its value the name of another variable without $ prefix E.g., if we have $addr, might have a statement $tmp.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
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
C# Programming: From Problem Analysis to Program Design1 Creating Your Own Classes C# Programming: From Problem Analysis to Program Design 4th Edition.
Creating Your Own Classes
Classes (Part 1) Lecture 3
Instant Scala.
CS-104 Final Exam Review Victor Norman.
Classes and Objects and Traits
Getting Functional.
Class Structure 7-Dec-18.
Cases and Classes and Case Classes
Getting Functional.
CS/ENGRD 2110 Fall 2018 Lecture 5: Local vars; Inside-out rule; constructors
String.
Classes and Objects and Traits
Python Review
Just Enough Java 17-May-19.
CS 240 – Advanced Programming Concepts
Presentation transcript:

Cases and Classes and Case Classes And Other Miscellany 16-Dec-15

Classes and constructors, I Every class has a constructor, which you write (no “invisible” constructors, as in Java) scala> class Person(val firstName:String, var lastName: String, age: Int) defined class Person The above is complete; no braces are needed unless you want to add code, fields, or methods The above defines: firstName (immutable) with getter function firstName lastName (mutable) with getter function lastName and setter function lastName_= The method name uses an underscore, but you use it as an ordinary assignment, for example, lastName = "Smith" Nothing for age (it can be used as a val in the rest of the constructor) 2

Classes and constructors, II Syntax: class ClassName ( parameters ) { body } The ClassName should begin with a capital letter and be CamelCase This is the constructor, and it has parameters A var parameter will cause a field, getter, and setter to be included: var p: Int gives the methods p: () => Int and p_=: Int => () These methods can be redefined inside the method A val parameter will create a field and a getter, but no setter A parameter with neither val nor var does not create a field or any methods, but it can be used within the body of the class When a new object of this class is defined, the fields are created, the methods are defined, and any “loose” code (not within a def ) is executed

Classes and constructors, III scala> class Person(val firstName:String, var lastName: String, age: Int) defined class Person scala> val mary = new Person("Mary", "Smith", 23) mary: Person = scala> mary.firstName res22: String = Mary scala> mary.lastName res23: String = Smith scala> mary.firstName = "Sally" :7: error: reassignment to val scala> mary.lastName = "Jones" res24: String = Jones scala> mary.age :8: error: value age is not a member of Person scala> mary.lastName res25: String = Jones 4

Classes and constructors, IV Again, but this time with a method: scala> class Person(val firstName:String, var lastName: String, age: Int) { | override def toString = firstName + " " + lastName + ", age " + age | } defined class Person scala> val mary = new Person("Mary", "Smith", 23) mary: Person = Mary Smith, age 23 scala> println(mary) Mary Smith, age 23 5

Auxiliary constructors A class (as on the previous slide) defines its primary constructor You can have additional, auxiliary constructors The first statement within an auxiliary constructor must be a call to another auxiliary constructor, or to the primary constructor Thus, every object creation eventually ends up at the primary constructor Syntax: def this( parameters1 ) { this( parameters2 ) … more code… } Since these are overloaded constructors, parameters1 and parameters2 must be different

Pattern matching with match You have seen pattern matching with match and literals today match { case "Saturday" => println("Party! Party! Party!") case "Sunday" => println("Pray....") case day => println(day + " is a workday. :( ") } You can match with 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! :( ") }

Pattern matching in assignments You can pattern match on tuples: scala> val (a, b, c) = (3, 5, 7) a: Int = 3 b: Int = 5 c: Int = 7 But… scala> val a, b, c = (3, 5, 7) a: (Int, Int, Int) = (3,5,7) b: (Int, Int, Int) = (3,5,7) c: (Int, Int, Int) = (3,5,7) You can pattern match on lists: scala> val list = List("once", "upon", "a", "time") list: List[java.lang.String] = List(once, upon, a, time) scala> val first :: second :: rest = list first: java.lang.String = once second: java.lang.String = upon rest: List[java.lang.String] = List(a, time)

Case classes If you declare a class as a case class, you get some extra features: It adds a factory method with the name of the class, so you can omit the word new when you create a new object All constructor parameters are implicitly val You get reasonable implementations of toString, hashCode, and equals “for free” Example: scala> case class Person(firstName: String, lastName: String) defined class Person scala> val jane = new Person("Jane", "Eyre") jane: Person = Person(Jane,Eyre) scala> val Person(f, l) = jane f: String = Jane l: String = Eyre scala> println(jane) Person(Jane,Eyre)

Operations and methods 10 As operationAs method call Unary prefix scala> -5 res4: Int = -5 scala> 5 unary_- res5: Int = -5 Unary scala> " abc " trim res6: java.lang.String = abc scala> " abc ".trim() res7: java.lang.String = abc Binary scala> "abc" + "xyz" res8: java.lang.String = abcxyz scala> "abcdef" substring 2 res10: java.lang.String = cdef scala> "abc".+("xyz") res9: java.lang.String = abcxyz scala> "abcdef".substring(2) res11: java.lang.String = cdef >2 operands scala> "abcdef" substring (1, 3) res12: java.lang.String = bc scala> "abcdef".substring(1, 3) res13: java.lang.String = bc

Parameters in braces A block consists of any number of statements inside braces, { } The last value in the block is the value of the block Parentheses, ( ), can’t enclose multiple statements When a method takes just one parameter, you can put that parameter inside braces instead of parentheses scala> "abcdefg" substring { 2 } res0: java.lang.String = cdefg This example is pointless and looks silly Sometimes, you may want to compute that parameter by a series of statements scala> println { | var x = 2 | while (x < 1000) x *= 2 | x | } 1024 This isn’t a great example either, but it does make the point 11

Methods with no parameters You can define a “parameterless” method: scala> def hello = println("Hello!") hello: Unit scala> hello Hello! scala> hello() :7: error: hello of type Unit does not take parameters You can define an “empty paren” method: scala> def hi() = println("Hi!") hi: ()Unit scala> hi Hi! scala> hi() Hi! If you define a method without parentheses, you can’t call it with parentheses You can replace a parameterless method with an empty paren method, without affecting user code (but not vice versa) 12

Uniform access In Java, the length of an array is a field, so you have to say myArray.length ; but the length of a String is a field, so you have to say myString.length() This violates the principle of uniform access: The user shouldn’t have to know whether it’s a field or a method However, if I say foo = bar, or println(bar), I am using bar like a variable, so I expect bar to act like a variable: bar should not do I/O bar should not change mutable state bar should not depend on values in mutable state In other words, if bar is a function, it should be a pure function Scala convention: When you call a method that does one of the above (impure) things, use parentheses 13

The End