Copyright 2018 Tendril, Inc. All rights reserved.

Size: px
Start display at page:

Download "Copyright 2018 Tendril, Inc. All rights reserved."

Transcription

1

2 Type Parameter Power-Up! Variance, Bounds, and Inference

3 INTRO Motivations 3

4 INTRO Motivations Home Energy Report Generation System Free Monad Workflow stages extending common base class Workflow actions parameterized with a Report type Different Reports extend Report base class Single reports, Optional reports, Lists of reports 4

5 INTRO Helpful Compiler is Helpful [info] Compiling 1 Scala source to /Users/cphelps/learning/type-parameter-powerup/target/scala-2.12/test-classes... [error] /Users/cphelps/learning/type-parameter-powerup/src/test/scala/example/VarianceSpec.scala:55:14: covariant type A occurs in contravariant position in type A of value newwrapped [error] def swap(newwrapped: A): Wrapper[A] = new Wrapper(newwrapped) [error] ^ [error] one error found 5

6 INTRO Helpful Compiler is Helpful [info] Compiling 1 Scala source to /Users/cphelps/learning/type-parameter-powerup/target/scala-2.12/test-classes... [error] /Users/cphelps/learning/type-parameter-powerup/src/test/scala/example/VarianceSpec.scala:55:14: covariant type A occurs in contravariant position in type A of value newwrapped [error] def swap(newwrapped: A): Wrapper[A] = new Wrapper(newwrapped) [error] ^ [error] one error found 6

7 INTRO Motivations 7

8 INTRO Motivations Users o Signatures of APIs what is it looking for? o What will the API accept? o How do I make the API interact with my domain class hierarchy? o How do I make sense of these weird error messages? API Designers o What do I want to allow? o What sorts of flexibility do I want to offer? o How do I make sense of these weird error messages? 8

9 How I stopped worrying about variance: Just add +/- until it compiles Adriaan Moors

10 INTRO Overview Variance Constraints and Typeclasses Dotty / Scala 3 10

11 Variance 11

12 VARIANCE Inheritance and Substitution All values have a type Types have a supertype relationship up to Any Types have a subtype relationship down to Nothing References can store subclass instances Functions can be passed subclass instances Functions can return subclass instances 12

13 VARIANCE Liskov Substitution Principle Subtype Requirement: Let ϕ ( x ) be a property provable about objects x of type T. Then ϕ ( y ) should be true for objects y of type S where S is a subtype of T. [Liskov and Wing, 1994] If S is a subtype of T, then objects of type T in a program may be replaced with objects of type S without altering any of the desirable properties of that program. [Wikipedia] 13

14 VARIANCE Higher-Kinded Types Generic Classes Types with parameters Contain or implemented in terms of another type o List[Int] o List[T] 14

15 VARIANCE Two Axes of Subclassing Container Superclass Contents Superclass Contents Subclass Container Subclass 15

16 VARIANCE Variance Defined Variance is the correlation of subtyping relationships of complex types and the subtyping relationships of their component types. [Tour of Scala] A central question that comes up when mixing OO with polymorphism is: if U is a subclass of T, is Container[U] considered a subclass of Container[T]? [Twitter Scala School] 16

17 VARIANCE Apply the LSP Variance is the correlation of when we can substitute complex types and the when we can substitute their component types. [Tour of Scala] A central question that comes up when mixing OO with polymorphism is: if U is a subclass of T, can Container[U] be substituted for Container[T]? [Twitter Scala School] 17

18 VARIANCE Substituting Compatible Machines 18

19 VARIANCE Domain Data Animal abstract class Animal { def name: String } abstract class Pet extends Animal case class Cat(name: String) extends Pet Pet case class Dog(name: String) extends Pet Cat Dog 19

20 VARIANCE Invariance The Default Case No subclass relationship Cannot substitute Container[T] for Container[U] unless T is U Subclasses SubContainer[T] can be substituted for Container[T] Exposed vars must be invariant Influences type inference 20

21 VARIANCE Invariance Examples Animal class InvariantWrapper[A](wrapped: A) { def unwrapped: A = wrapped } val w: InvariantWrapper[Cat] = new InvariantWrapper(Cat( Morris")) Pet class SubWrapper[A](wrapped: A) extends InvariantWrapper(wrapped) {} Cat Dog val sw: InvariantWrapper[Cat] = new SubWrapper(Cat("Milo")) val aw: InvariantWrapper[Animal] = new InvariantWrapper[Cat](Cat("Bill")) 21

22 VARIANCE Invariance Examples Animal class InvariantWrapper[A](wrapped: A) { def unwrapped: A = wrapped } val w: InvariantWrapper[Cat] = new InvariantWrapper(Cat( Morris")) Pet class SubWrapper[A](wrapped: A) extends InvariantWrapper(wrapped) {} Cat Dog val sw: InvariantWrapper[Cat] = new SubWrapper(Cat("Milo")) type mismatch; found: InvariantWrapper[Cat] val aw: required: InvariantWrapper[Animal] = Note: example.cat <: example.animal, new but InvariantWrapper[Cat](Cat("Bill")) class is invariant in type A. 22

23 VARIANCE Covariance Sources of Values Subclass relationship when contents have a subclass relationship Can substitute Container[U] for Container[T] if U is a subclass of T Useful for extracting the contents of the container o Instances of U can be used where T instances are expected o Container[U] will produce T instances o Types are sound Problematic when adding or changing values 23

24 VARIANCE Covariance Examples class CovariantWrapper[+A](wrapped: A) { def unwrapped: A = wrapped } Animal def doit(thing: CovariantWrapper[Animal]) =??? Pet doit(new CovariantWrapper[Cat](Cat("Garfield"))) doit(new CovariantWrapper[Dog](Dog( Odie ))) Cat Dog doit(new CovariantWrapper[Any](Cat("Nermal"))) 24

25 VARIANCE Covariance Examples class CovariantWrapper[+A](wrapped: A) { def unwrapped: A = wrapped } Animal def doit(thing: CovariantWrapper[Animal]) =??? Cat Pet doit(new CovariantWrapper[Cat](Cat("Garfield"))) doit(new CovariantWrapper[Dog](Dog( Odie ))) Dog doit(new CovariantWrapper[Any](Cat("Nermal"))) type mismatch; found: CovariantWrapper[Any] required: CovariantWrapper[Animal] 25

26 VARIANCE Contravariance Consumers of Values Subclass relationship when contents have a superclass relationship Can substitute Container[T] for Container[U] if T is a superclass of U Useful for processors or consumers of values o Instances of U can be used where T instances are expected o Consumer[U] can consume T instances o Types are sound Problematic when returning or producing values 26

27 VARIANCE Contravariance Examples Animal abstract class Keeper[-A] { def tend(input: A): Unit } class DogSitter extends Keeper[Dog] { override def tend(input: Dog): Unit =??? } class ZooKeeper extends Keeper[Animal] {... } class PetSitter extends Keeper[Pet] {... } Cat Pet Dog val ds: Keeper[Dog] = new DogSitter ds.tend(dog("tintin")) val zoo: Keeper[Dog] = new ZooKeeper zoo.tend(dog("scooby")) val petco: Keeper[Pet] = new DogSitter petco.tend(dog("ceasar")) 27

28 VARIANCE Contravariance Examples Animal abstract class Keeper[-A] { def tend(input: A): Unit } class DogSitter extends Keeper[Dog] { override def tend(input: Dog): Unit =??? } class ZooKeeper extends Keeper[Animal] {... } class PetSitter extends Keeper[Pet] {... } Cat Pet Dog val ds: Keeper[Dog] = new DogSitter ds.tend(dog("tintin")) val zoo: Keeper[Dog] = new ZooKeeper zoo.tend(dog("scooby")) val petco: Keeper[Pet] = new DogSitter type mismatch; found : DogSitter required: Keeper[example.Pet] petco.tend(dog("ceasar")) 28

29 VARIANCE Positions Covariant Position method returns Contravariant Position method arguments Invariant Position - mutable vars Covariant parameters cannot appear in contravariant position Contravariant parameters cannot appear in covariant position Covariant or contravariant parameters cannot appear in invariant position o Scala and IntelliJ error messages misleading 29

30 VARIANCE The Problem with Contravariant Positions class Box[+Pet](p: Pet) { // won't compile Covariant in contravariant pos def swap(newp: Pet): Box[Pet] = new Box[Pet](newp) } val mypet = new Box[Cat](Cat( Morris )) // Seems okay so far mypet.swap(cat("cassie")) // Oops, we can't store a Dog in a Box[Cat] mypet.swap(dog("ceasar")) 30

31 VARIANCE The Problem with Covariant Positions class Sitter[-Pet](p: Pet) { // won't compile - contravariant in covariant pos def walk(): Pet =??? } val mysitter: Sitter[Cat] = new Sitter[Pet](Cat("Doraemon")) // seems okay val walkedpet: Pet = mysitter.walk() // if walk returns a Cat, everything is ok // if it returns a Dog, we have a problems // if it returns a Pet, we have a problem. val walked: Cat = mysitter.walk() 31

32 VARIANCE Function Inputs Animal Pet val p1: Pet val p2: Pet f(p1, p2) def f(a: Pet, b: Pet): Pet def f(a: Animal, b: Pet): Pet def f(a: Any, b: Pet): Pet def f(a: Any, b: Any): Pet Cat Dog def f(a: Cat, b: Dog): Pet Function2[-T1, -T2, R] 32

33 VARIANCE Function Outputs Animal Pet val p1: Pet val p2: Pet val r: Animal = f(p1, p2) def f(a: Pet, b: Pet): Animal def f(a: Pet, b: Pet): Pet def f(a: Pet, b: Pet): Cat Cat Dog def f(a: Pet, b: Pet): Any Function2[-T1, -T2, +R] 33

34 VARIANCE When to Use Covariance o Containers o Producers o Representing inputs Contravariance o Consumers o Processors or Visitors o Representing outputs Invariance o Distinct types o Markers or Labels o Influence inference 34

35 Constraints and Typeclasses 35

36 CONSTRAINTS AND TYPECLASSES Upper and Lower Bounds Constrain the valid types Upper bound parameter is same or subtype o def pet[p <: Pet](animal: P): Unit =??? Lower bound parameter is same or supertype o def pre[b >: A](x: B, xs: List[A]): List[B] =???

37 CONSTRAINTS AND TYPECLASSES Bounds and Variance abstract class List[+A] {... } case object Nil extends List[Nothing] {... } case class Cons[B] (elem: B, tail: List[B]) extends List[B] {... } 37

38 CONSTRAINTS AND TYPECLASSES Bounds and Variance abstract class List[+A] { } def prepend(elem: A): List[A] =??? case object Nil extends List[Nothing] {... } case class Cons[B] (elem: B, tail: List[B]) extends List[B] {... } 38

39 CONSTRAINTS AND TYPECLASSES Bounds and Variance abstract class List[+A] { } def prepend(elem: A): List[A] =??? covariant type A occurs in contravariant position in type A of value elem case object Nil extends List[Nothing] {... } case class Cons[B] (elem: B, tail: List[B]) extends List[B] {... } 39

40 CONSTRAINTS AND TYPECLASSES Bounds and Variance abstract class List[+A] { def prepend[b](elem: B): List[B] = new Cons(elem, this) } case object Nil extends List[Nothing] {... } case class Cons[B] (elem: B, tail: List[B]) extends List[B] {... } 40

41 CONSTRAINTS AND TYPECLASSES Bounds and Variance abstract class List[+A] { def prepend[b](elem: B): List[B] = new Cons(elem, this) } type mismatch; found: List[A] required: List[B] case object Nil extends List[Nothing] {... } case class Cons[B] (elem: B, tail: List[B]) extends List[B] {... } 41

42 CONSTRAINTS AND TYPECLASSES Bounds and Variance abstract class List[+A] { } def prepend[b >: A] (elem: B): List[B] =??? case object Nil extends List[Nothing] {... } case class Cons[B] (elem: B, tail: List[B]) extends List[B] {... } 42

43 CONSTRAINTS AND TYPECLASSES Change to a Wider Type scala> List(1, 2, 3, 4, 5) res0: List[Int] = List(1, 2, 3, 4, 5) scala> 0 :: res0 res1: List[Int] = List(0, 1, 2, 3, 4, 5) scala> 1.5 :: res0 res2: List[AnyVal] = List(1.5, 1, 2, 3, 4, 5) scala> res2(0) res3: AnyVal = 1.5 scala> res2(1) res4: AnyVal = 1 43

44 CONSTRAINTS AND TYPECLASSES View Bounds Deprecated from 2.11 [ A <% B ] Indicates A is convertable to B by implicit conversion Introduces evidence parameter o def view[aa <% A](x: AA): A =??? o def view$[aa](x: AA)(implicit ev1$: AA => A) =??? 44

45 CONSTRAINTS AND TYPECLASSES Context Bounds [ A : Ctx ] Indicates A has some context Ctx o There exists a Ctx[A] in implicit scope Introduces an evidence parameter o def ctxbound[x: M](x: X) =??? o def ctxbound[x](x: X)(implicit ev1$: M[X]) =??? Access the context with the implicitly keyword o val m = implicitly[m[x]] o m.somemethod() 45

46 CONSTRAINTS AND TYPECLASSES Typeclass Pattern External implementation of an interface o No need to extend directly o Possible without access to class source Introduce via a context bound Implement in terms of of other instances o Adder[Pair[Int]] defined in terms of Adder[Int] 46

47 CONSTRAINTS AND TYPECLASSES Typeclass Pattern Define an interface Implement for your class Introduce to implicit scope Pass to function as implicit parameter OR as type constraint Call methods from the interface 47

48 CONSTRAINTS AND TYPECLASSES Typeclass Example trait Adder[A] { def add(x: A, y: A): A } implicit val IntAdder = new Adder[Int] { override def add(x: Int, y: Int): Int = x + y } def addthings[t: Adder](x: T, y: T): T = { implicitly[adder[t]].add(x, y) } addthings(5, 7) 48

49 Inductive Typeclass Definition case class Pair[T](fst: T, snd: T) implicit def pairadder[t: Adder] = new Adder[Pair[T]] { override def add(x: Pair[T], y: Pair[T]): Pair[T] = { val ta = implicitly[adder[t]] Pair(ta.add(x.fst, y.fst), ta.add(x.snd, y.snd)) } } 49

50 DOTTY Dotty / Scala 3

51 DOTTY Dotty Changes Scala 3 is fundamentally the same language as Scala 2 Variance and type bounds still exist essentially the same o Current dotc slightly different error messages No existential types (but other constructs instead) Structural types different implementation

52 Takeaways Variance o Substitution o Arises naturally as a consequence of Liskov Substitution o Deeply entwined with subclassing in higher-kinded types Bounds o Interact with variance -> widening o Interact with implicits -> typeclasses 52

53 @CJPhelps github.com/chrisphelps/type-parameter-power-up

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example

Overview. Elements of Programming Languages. Advanced constructs. Motivating inner class example Overview Elements of Programming Languages Lecture 11: Object-oriented functional programming James Cheney University of Edinburgh October 30, 2017 We ve now covered: basics of functional programming (with

More information

CompSci 220. Programming Methodology 12: Functional Data Structures

CompSci 220. Programming Methodology 12: Functional Data Structures CompSci 220 Programming Methodology 12: Functional Data Structures A Polymorphic Higher- Order Function def findfirst[a](as: Array[A], p: A => Boolean): Int = { def loop(n: Int): Int = if (n >= as.length)

More information

The SCAlable LAnguage

The SCAlable LAnguage The SCAlable LAnguage The Scala Language: Object Oriented Functional Programming Gabor Szokoli Overview Introduction Everything is an Object Inheritance and mixins For comprehensions Generic Types: Covariance,

More information

Refactoring Java Generics by Inferring Wildcards, In Practice

Refactoring Java Generics by Inferring Wildcards, In Practice Refactoring Java Generics by Inferring Wildcards, In Practice John Altidor & Yannis Smaragdakis Outline Background on variance Motivate adding Java wildcards to code Refactoring tool for adding Java wildcards

More information

Exercise 8 Parametric polymorphism November 18, 2016

Exercise 8 Parametric polymorphism November 18, 2016 Concepts of Object-Oriented Programming AS 2016 Exercise 8 Parametric polymorphism November 18, 2016 Task 1 Consider the following Scala classes: class A class B extends A class P1[+T] class P2[T

More information

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes INF 212/CS 253 Type Systems Instructors: Harry Xu Crista Lopes What is a Data Type? A type is a collection of computational entities that share some common property Programming languages are designed to

More information

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A. HAS-A Relationship Association is a weak relationship where all objects have their own lifetime and there is no ownership. For example, teacher student; doctor patient. If A uses B, then it is an aggregation,

More information

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors. INF 212 ANALYSIS OF PROG. LANGS Type Systems Instructors: Crista Lopes Copyright Instructors. What is a Data Type? A type is a collection of computational entities that share some common property Programming

More information

The DOT Calculus. (Dependent Object Types) Nada Amin. May 12, flatmap(oslo)

The DOT Calculus. (Dependent Object Types) Nada Amin. May 12, flatmap(oslo) The DOT Calculus (Dependent Object Types) Nada Amin flatmap(oslo) May 12, 2014 1 Types in Scala and DOT 2 Types in Scala modular named type scala.collection.bitset compound type Channel with Logged refined

More information

Side-effect checking for Scala. Lukas Rytz, Martin Odersky, Adriaan Moors Scala Days 2011

Side-effect checking for Scala. Lukas Rytz, Martin Odersky, Adriaan Moors Scala Days 2011 Side-effect checking for Scala Lukas Rytz, Martin Odersky, Adriaan Moors Scala Days 2011 Why effect checking? We have at least one post a week where the correct answer is wholly or in part, effect system.

More information

CS Programming Languages: Scala

CS Programming Languages: Scala CS 3101-2 - Programming Languages: Scala Lecture 5: Exceptions, Generic Classes Daniel Bauer (bauer@cs.columbia.edu) November 19, 2014 Daniel Bauer CS3101-2 Scala - 05 - Exceptions, Generic Classes 1/28

More information

Linked lists and the List class

Linked lists and the List class Linked lists and the List class Cheong 1 Linked lists So far, the only container object we used was the array. An array is a single object that contains references to other objects, possibly many of them.

More information

Programming in Scala Second Edition

Programming in Scala Second Edition Programming in Scala Second Edition Martin Odersky, Lex Spoon, Bill Venners artima ARTIMA PRESS WALNUT CREEK, CALIFORNIA Contents Contents List of Figures List of Tables List of Listings Foreword Foreword

More information

The DOT Calculus. (Dependent Object Types) Nada Amin. June 18, Scala Days

The DOT Calculus. (Dependent Object Types) Nada Amin. June 18, Scala Days The DOT Calculus (Dependent Object Types) Nada Amin Scala Days June 18, 2014 1 DOT: Dependent Object Types DOT is a core calculus for path-dependent types. Goals simplify Scala s type system by desugaring

More information

Imperative Programming 2: Traits

Imperative Programming 2: Traits Imperative Programming 2: Traits Hongseok Yang University of Oxford Experience with traits so far In IP1, you have used traits as interfaces, in order to specify available methods and fields. trait IntQueue

More information

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA CSE 3302 Lecture 7: Polymorphism and generics 16 September 2010 Nate Nystrom UTA 2 Polymorphism poly = many morph = shape Allow a variable to contain values with different types 3 Subtype polymorphism

More information

Chapter 5 Object-Oriented Programming

Chapter 5 Object-Oriented Programming Chapter 5 Object-Oriented Programming Develop code that implements tight encapsulation, loose coupling, and high cohesion Develop code that demonstrates the use of polymorphism Develop code that declares

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2017 Lecture 10a Andrew Tolmach Portland State University 1994-2017 Object-oriented Programming Programs are structured in terms of objects: collections of variables

More information

The Trouble with Types

The Trouble with Types The Trouble with Types Martin Odersky EPFL and Typesafe Types Everyone has an opinion on them Industry: Used to be the norm (C/C++, Java). Today split about evenly with dynamic. Academia: Static types

More information

Java Wildcards Meet Definition-Site Variance

Java Wildcards Meet Definition-Site Variance Java Wildcards Meet Definition-Site Variance John Altidor 1 Christoph Reichenbach 2,1 Yannis Smaragdakis 3,1 1 University of Massachusetts 2 Google 3 University of Athens Outline Motivation for Variance.

More information

CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping. Dan Grossman Winter 2013 CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping Dan Grossman Winter 2013 Now Use what we learned about subtyping for records and functions to understand

More information

CSCI-GA Final Exam

CSCI-GA Final Exam CSCI-GA 2110-003 - Final Exam Instructor: Thomas Wies Name: Sample Solution ID: You have 110 minutes time. There are 7 assignments and you can reach 110 points in total. You can solve the exercises directly

More information

21 Subtyping and Parameterized Types

21 Subtyping and Parameterized Types Object-Oriented Design Lecture 21 CS 3500 Spring 2011 (Pucella) Friday, Apr 1, 2011 21 Subtyping and Parameterized Types Given a parameterized type Foo[T], suppose we know that A B (A is a subtype of B),

More information

Scala, Your Next Programming Language

Scala, Your Next Programming Language Scala, Your Next Programming Language (or if it is good enough for Twitter, it is good enough for me) WORLDCOMP 2011 By Dr. Mark C. Lewis Trinity University Disclaimer I am writing a Scala textbook that

More information

Exercise 8 Parametric polymorphism November 17, 2017

Exercise 8 Parametric polymorphism November 17, 2017 Concepts of Object-Oriented Programming AS 2017 Exercise 8 Parametric polymorphism November 17, 2017 Task 1 Implement a list in Java or C# with two methods: public void add(int i, Object el) public Object

More information

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018 Contents 1 Mutation in the Doghouse 1 1.1 Aside: Access Modifiers..................................

More information

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline

Bibliography. Analyse et Conception Formelle. Lesson 5. Crash Course on Scala. Scala in a nutshell. Outline Bibliography Analyse et Conception Formelle Lesson 5 Crash Course on Scala Simply Scala. Onlinetutorial: http://www.simply.com/fr http://www.simply.com/ Programming in Scala, M. Odersky, L. Spoon, B. Venners.

More information

First IS-A Relationship: Inheritance

First IS-A Relationship: Inheritance First IS-A Relationship: Inheritance The relationships among Java classes form class hierarchy. We can define new classes by inheriting commonly used states and behaviors from predefined classes. A class

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 10: James Cheney University of Edinburgh October 23, 2017 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

More About Objects. Zheng-Liang Lu Java Programming 255 / 282 More About Objects Inheritance: passing down states and behaviors from the parents to their children. Interfaces: requiring objects for the demanding methods which are exposed to the outside world. Polymorphism

More information

an overview Alceste Scalas Programming languages reading group

an overview Alceste Scalas Programming languages reading group an overview Alceste Scalas Programming languages reading group 31 October 2017 Scala: what s the hype about? Object oriented and functional programming language Runs on the JVM... interoperability with

More information

Improving Scala's Safe Type-Level Abstraction

Improving Scala's Safe Type-Level Abstraction Seminar: Program Analysis and Transformation University of Applied Sciences Rapperswil Improving Scala's Safe Type-Level Abstraction Stefan Oberholzer, soberhol@hsr.ch Dez 2010 Abstract Scala cannot nd

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Fall 2017 Lecture 7b Andrew Tolmach Portland State University 1994-2017 Type Inference Some statically typed languages, like ML (and to a lesser extent Scala), offer alternative

More information

Static and Dynamic Behavior עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מובסס על הרצאות של אותו קורס שניתן בשנים הקודמות ע "י ד"ר גרא וייס

Static and Dynamic Behavior עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מובסס על הרצאות של אותו קורס שניתן בשנים הקודמות ע י דר גרא וייס Static and Dynamic Behavior עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מובסס על הרצאות של אותו קורס שניתן בשנים הקודמות ע "י ד"ר גרא וייס 2 Roadmap In this chapter we will examine how differences

More information

Lecture 09: Introduction to Scala

Lecture 09: Introduction to Scala Lecture 09: Introduction to Scala Computer Science Department, University of Crete Multicore Processor Programming Based on slides by D. Malayeri, S.D. Vick, P. Haller, and M. Madsen Pratikakis (CSD) Scala

More information

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007

Object Fundamentals Part Three. Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007 Object Fundamentals Part Three Kenneth M. Anderson University of Colorado, Boulder CSCI 4448/6448 Lecture 4 09/06/2007 1 Lecture Goals Continue our tour of the basic concepts, terminology, and notations

More information

Type Hierarchy. Lecture 6: OOP, autumn 2003

Type Hierarchy. Lecture 6: OOP, autumn 2003 Type Hierarchy Lecture 6: OOP, autumn 2003 The idea Many types have common behavior => type families share common behavior organized into a hierarchy Most common on the top - supertypes Most specific at

More information

CSE 130, Fall 2006: Final Examination

CSE 130, Fall 2006: Final Examination CSE 130, Fall 2006: Final Examination Name: ID: Instructions, etc. 1. Write your answers in the space provided. 2. Wherever it says explain, write no more than three lines as explanation. The rest will

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Week 13 - Part 1 Thomas Wies New York University Review Last lecture Object Oriented Programming Outline Today: Scala Sources: Programming in Scala, Second

More information

Advanced Object-Oriented Languages Scala

Advanced Object-Oriented Languages Scala Advanced Object-Oriented Languages Scala Programming Paradigms Department of Computer Science University of Aalborg, Denmark Erik Ernst (U. of Aarhus) Overview Purpose of using Scala Introduction syntax

More information

Functional Programming

Functional Programming Functional Programming Midterm Solution Friday, November 6 2015 Exercise 1: List functions (10 points) You are asked to implement the following List functions using only the specified List API methods.

More information

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington CSE 3302 Lecture 3: Objects 2 September 2010 Nate Nystrom University of Texas at Arlington Administration Out of town this afternoon thru Monday HW1 due next Thursday 9/9 Types Last time: strongly typed

More information

ob-ject: to feel distaste for something Webster's Dictionary

ob-ject: to feel distaste for something Webster's Dictionary Objects ob-ject: to feel distaste for something Webster's Dictionary Prof. Clarkson Fall 2017 Today s music: Kung Fu Fighting by CeeLo Green Review Currently in 3110: Advanced topics Futures Monads Today:

More information

Under the Hood of Scala Implicits. by Alexander Podkhalyuzin ScalaDays San Francisco 2015

Under the Hood of Scala Implicits. by Alexander Podkhalyuzin ScalaDays San Francisco 2015 Under the Hood of Scala Implicits by Alexander Podkhalyuzin ScalaDays San Francisco 2015 Agenda How implicits work How IDE can help with them Possibilities to improve performance of compilation and IDE

More information

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017] 301AA - Advanced Programming [AP-2017] Lecturer: Andrea Corradini andrea@di.unipi.it Tutor: Lillo GalleBa galleba@di.unipi.it Department of Computer Science, Pisa Academic Year 2017/18 AP-2017-12: Polymorphisms

More information

More Relationships Between Classes

More Relationships Between Classes More Relationships Between Classes Inheritance: passing down states and behaviors from the parents to their children Interfaces: grouping the methods, which belongs to some classes, as an interface to

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 class Point { 2... 3 private static int numofpoints = 0; 4 5 Point() { 6 numofpoints++; 7 } 8 9 Point(int x, int y) { 10 this(); // calling the constructor with no input argument;

More information

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016

CSE341: Programming Languages Lecture 11 Type Inference. Dan Grossman Spring 2016 CSE341: Programming Languages Lecture 11 Type Inference Dan Grossman Spring 2016 Type-checking (Static) type-checking can reject a program before it runs to prevent the possibility of some errors A feature

More information

Records. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05

Records. ADTs. Objects as Records. Objects as ADTs. Objects CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 15: Objects 25 Feb 05 Records CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 15: Objects 25 Feb 05 Objects combine features of records and abstract data types Records = aggregate data structures Combine several

More information

Overview. Elements of Programming Languages. Another example. Consider the humble identity function

Overview. Elements of Programming Languages. Another example. Consider the humble identity function Overview Elements of Programming Languages Lecture 8: Polymorphism and type inference James Cheney University of Edinburgh October 21, 2016 This week and next week, we will cover di erent forms of abstraction

More information

Generalized Code. Fall 2011 (Honors) 2

Generalized Code. Fall 2011 (Honors) 2 CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy

More information

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Week 14 - Part 1 Thomas Wies New York University Review Last lecture Exceptions Outline Today: Generic Programming Sources for today s lecture: PLP, ch. 8.4

More information

Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון Static and Dynamic Behavior לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון 22 Roadmap In this chapter we will examine how differences in static and dynamic features effect object-oriented programming

More information

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner. HAS-A Relationship Association is a relationship where all objects have their own lifecycle and there is no owner. For example, teacher student Aggregation is a specialized form of association where all

More information

Example: Count of Points

Example: Count of Points Example: Count of Points 1 public class Point { 2... 3 private static int numofpoints = 0; 4 5 public Point() { 6 numofpoints++; 7 } 8 9 public Point(int x, int y) { 10 this(); // calling Line 5 11 this.x

More information

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון Overriding עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap A method in a child class overrides a method in the parent class if it has the same name and type signature: Parent void method(int,float)

More information

Software Engineering: Design & Construction

Software Engineering: Design & Construction Software Engineering: Design & Construction Department of Computer Science Software Technology Group Practice Exam May 22, 2015 First Name Last Name Matriculation Number Course of Study Department Signature

More information

Inheritance and object compatibility

Inheritance and object compatibility Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not the other way around Examples: reference/pointer can

More information

Life in a Post-Functional World

Life in a Post-Functional World Life in a Post-Functional World Definitions Functional Programming Definitions Functional Programming Programming with functions! Definitions Functional Programming Programming with functions! Functions

More information

Imperative Programming 2: Inheritance 1

Imperative Programming 2: Inheritance 1 Imperative Programming 2: Inheritance 1 Hongseok Yang University of Oxford Motivation Scala programs consist of classes, traits and singleton objects. Inheritance is a fundamental building block for relating

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract Classes

More information

CS558 Programming Languages

CS558 Programming Languages CS558 Programming Languages Winter 2018 Lecture 7b Andrew Tolmach Portland State University 1994-2018 Dynamic Type Checking Static type checking offers the great advantage of catching errors early And

More information

Object-Oriented Programming More Inheritance

Object-Oriented Programming More Inheritance Object-Oriented Programming More Inheritance Ewan Klein School of Informatics Inf1 :: 2009/10 Ewan Klein (School of Informatics) OOP: More Inheritance Inf1 :: 2009/10 1 / 45 1 Inheritance Flat Hierarchy

More information

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding Conformance Conformance and Class Invariants Same or Better Principle Access Conformance Contract Conformance Signature Conformance Co-, Contra- and No-Variance Overloading and Overriding Inheritance as

More information

CMSC 202. Generics II

CMSC 202. Generics II CMSC 202 Generics II Generic Sorting We can now implement sorting functions that can be used for any class (that implements Comparable). The familiar insertion sort is shown below.!! public static

More information

CS152: Programming Languages. Lecture 24 Bounded Polymorphism; Classless OOP. Dan Grossman Spring 2011

CS152: Programming Languages. Lecture 24 Bounded Polymorphism; Classless OOP. Dan Grossman Spring 2011 CS152: Programming Languages Lecture 24 Bounded Polymorphism; Classless OOP Dan Grossman Spring 2011 Revenge of Type Variables Sorted lists in ML (partial): type a slist make : ( a -> a -> int) -> a slist

More information

Rushikesh K Joshi. Department of Computer Science and Engineering Indian Institute of Technology Bombay

Rushikesh K Joshi. Department of Computer Science and Engineering Indian Institute of Technology Bombay CS 617 Object Oriented Systems Lecture 9 Polymorphism: Mere Syntactic Vs. Dynamic Binding,, Subsumption Covariance, Contravariance 3:30-5:00 pm Thu, Jan 31 Rushikesh K Joshi Department of Computer Science

More information

Overview. Elements of Programming Languages. Objects. Self-Reference

Overview. Elements of Programming Languages. Objects. Self-Reference Overview Elements of Programming Languages Lecture 11: James Cheney University of Edinburgh November 3, 2015 Last time: programming in the large Programs, packages/namespaces, importing Modules and interfaces

More information

[ L5P1] Object-Oriented Programming: Advanced Concepts

[ L5P1] Object-Oriented Programming: Advanced Concepts [ L5P1] Object-Oriented Programming: Advanced Concepts Polymorphism Polymorphism is an important and useful concept in the object-oriented paradigm. Take the example of writing a payroll application for

More information

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08 CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 17: Types and Type-Checking 25 Feb 08 CS 412/413 Spring 2008 Introduction to Compilers 1 What Are Types? Types describe the values possibly

More information

Optimizing Higher-Order Functions in Scala

Optimizing Higher-Order Functions in Scala Optimizing Higher-Order Functions in Scala Iulian Dragos EPFL Outline A quick tour of Scala Generalities Extension through libraries Closure translation in Scala Cost Optimizations in the Scala compiler

More information

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia Object Oriented Programming in Java Jaanus Pöial, PhD Tallinn, Estonia Motivation for Object Oriented Programming Decrease complexity (use layers of abstraction, interfaces, modularity,...) Reuse existing

More information

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs. Local Variable Initialization Unlike instance vars, local vars must be initialized before they can be used. Eg. void mymethod() { int foo = 42; int bar; bar = bar + 1; //compile error bar = 99; bar = bar

More information

Computer Science 225 Advanced Programming Siena College Spring Topic Notes: Inheritance

Computer Science 225 Advanced Programming Siena College Spring Topic Notes: Inheritance Computer Science 225 Advanced Programming Siena College Spring 2017 Topic Notes: Inheritance Our next topic is another that is fundamental to object-oriented design: inheritance. Inheritance allows a programmer

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Polymorphism 1 / 19 Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll.

More information

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3 Course Code: GK1965 Overview Java 8 Essentials for OO Developers is a three-day, fast-paced, quick start to Java 8 training

More information

Implementing Method Type Specialisation In Dotty

Implementing Method Type Specialisation In Dotty École Polytechnique Fédérale de Lausanne Semester Project - LAMP Report Implementing Method Type Specialisation In Dotty Author: Alexandre Sikiaridis Supervised by: Dmitry Petrashko Martin Odersky 05/06/2015

More information

Introduction to Type Driven Development in Scala

Introduction to Type Driven Development in Scala Introduction to Type Driven Development in Scala Marcus A. Henry, Jr. @dreadedsoftware Software Engineer @integrichain 1 def f(a: Int, b: Int): String = { a.tostring + b.tostring This is a function 2 def

More information

Overview. Elements of Programming Languages. Records. Named variants. Last time: Simple data structures: pairing (product types), choice (sum types)

Overview. Elements of Programming Languages. Records. Named variants. Last time: Simple data structures: pairing (product types), choice (sum types) Overview Elements of Programming Languages Lecture 7: Records, variants, and subtyping James Cheney University of Edinburgh October 12, 2017 Last time: Simple data structures: pairing (product types),

More information

What is Inheritance?

What is Inheritance? Inheritance 1 Agenda What is and Why Inheritance? How to derive a sub-class? Object class Constructor calling chain super keyword Overriding methods (most important) Hiding methods Hiding fields Type casting

More information

Comp215: Thinking Generically

Comp215: Thinking Generically Comp215: Thinking Generically Dan S. Wallach (Rice University) Copyright 2015, Dan S. Wallach. All rights reserved. Functional APIs On Wednesday, we built a list of Objects. This works. But it sucks. class

More information

Programming II (CS300)

Programming II (CS300) 1 Programming II (CS300) Chapter 05: Inheritance and Interfaces MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Inheritance and Interfaces 2 Introduction Inheritance and Class Hierarchy Polymorphism Abstract

More information

CSE 505, Fall 2007, Final Examination 10 December Please do not turn the page until everyone is ready.

CSE 505, Fall 2007, Final Examination 10 December Please do not turn the page until everyone is ready. CSE 505, Fall 2007, Final Examination 10 December 2007 Please do not turn the page until everyone is ready. Rules: The exam is closed-book, closed-note, except for one side of one 8.5x11in piece of paper.

More information

Exercise: Singleton 1

Exercise: Singleton 1 Exercise: Singleton 1 In some situations, you may create the only instance of the class. 1 class mysingleton { 2 3 // Will be ready as soon as the class is loaded. 4 private static mysingleton Instance

More information

Symmetry in Type Theory

Symmetry in Type Theory Google May 29th, 2012 What is Symmetry? Definition Symmetry: Two or more things that initially look distinct, may actually be instances of a more general underlying principle. Why do we care? Simplicity.

More information

Object-Oriented Design

Object-Oriented Design Object-Oriented Design Lecturer: Raman Ramsin Lecture 9: Generalization/Specialization 1 Analysis Workflow: Analyze a Use Case The analysis workflow consists of the following activities: Architectural

More information

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6] 1 Lecture Overview Types 1. Type systems 2. How to think about types 3. The classification of types 4. Type equivalence structural equivalence name equivalence 5. Type compatibility 6. Type inference [Scott,

More information

INSTRUCTIONS TO CANDIDATES

INSTRUCTIONS TO CANDIDATES NATIONAL UNIVERSITY OF SINGAPORE SCHOOL OF COMPUTING MIDTERM ASSESSMENT FOR Semester 2 AY2017/2018 CS2030 Programming Methodology II March 2018 Time Allowed 90 Minutes INSTRUCTIONS TO CANDIDATES 1. This

More information

Scala. Fernando Medeiros Tomás Paim

Scala. Fernando Medeiros Tomás Paim Scala Fernando Medeiros fernfreire@gmail.com Tomás Paim tomasbmp@gmail.com Topics A Scalable Language Classes and Objects Basic Types Functions and Closures Composition and Inheritance Scala s Hierarchy

More information

Inheritance & Polymorphism

Inheritance & Polymorphism Inheritance & Polymorphism Procedural vs. object oriented Designing for Inheritance Test your Design Inheritance syntax **Practical ** Polymorphism Overloading methods Our First Example There will be shapes

More information

Thanks! Review. Course Goals. General Themes in this Course. There are many programming languages. Teaching Assistants. John Mitchell.

Thanks! Review. Course Goals. General Themes in this Course. There are many programming languages. Teaching Assistants. John Mitchell. 1 CS 242 Thanks! Review John Mitchell Final Exam Wednesday Dec 8 8:30 11:30 AM Gates B01, B03 Teaching Assistants Mike Cammarano TJ Giuli Hendra Tjahayadi Graders Andrew Adams Kenny Lau Vishal Patel and

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Object-Oriented Programming Review 2: Object-Oriented Programming Christopher Simpkins chris.simpkins@gatech.edu CS 1331 (Georgia Tech) Review 2: Object-Oriented Programming 1 / 14 Topics

More information

Object Oriented Issues in VDM++

Object Oriented Issues in VDM++ Object Oriented Issues in VDM++ Nick Battle, Fujitsu UK (nick.battle@uk.fujitsu.com) Background VDMJ implemented VDM-SL first (started late 2007) Formally defined. Very few semantic problems VDM++ support

More information

n n Try tutorial on front page to get started! n spring13/ n Stack Overflow!

n   n Try tutorial on front page to get started! n   spring13/ n Stack Overflow! Announcements n Rainbow grades: HW1-6, Quiz1-5, Exam1 n Still grading: HW7, Quiz6, Exam2 Intro to Haskell n HW8 due today n HW9, Haskell, out tonight, due Nov. 16 th n Individual assignment n Start early!

More information

Subtype Polymorphism

Subtype Polymorphism Subtype Polymorphism For convenience, let U be a subtype of T. Liskov Substitution Principle states that T-type objects may be replaced with U-type objects without altering any of the desirable properties

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018

CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods. Dan Grossman Autumn 2018 CSE341: Programming Languages Lecture 23 Multiple Inheritance, Mixins, Interfaces, Abstract Methods Dan Grossman Autumn 2018 What next? Have used classes for OOP's essence: inheritance, overriding, dynamic

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 22 Polymorphism using Interfaces Overview Problem: Can we delay decisions regarding which method to use until run time? Polymorphism Different methods

More information