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

Similar documents
CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Parametric polymorphism and Generics

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

CSE 331 Software Design & Implementation

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017]

Exercise 8 Parametric polymorphism November 18, 2016

Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

Java Generics -- an introduction. Based on

CSCE 314 Programming Languages

Polymorphism (generics)

CSE 331. Generics (Parametric Polymorphism)

CS558 Programming Languages

CS558 Programming Languages

CSE 331 Software Design & Implementation

PARAMETRIC POLYMORPHISM

Software Engineering. Prof. Agostino Poggi

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

Primitive Java Generic Class

Java Design Goals. Lecture 32: Java. Java Original implementations slow! Exceptions & Subtyping. - void method readfiles() throws IOException {...}!

Exercise 8 Parametric polymorphism November 17, 2017

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

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

The collections interfaces

Generic programming in OO Languages

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

6. Generic and Virtual Types

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

CSE 331 Software Design & Implementation

CS6202: Advanced Topics in Programming Languages and Systems Lecture 0 : Overview

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

generic programming alberto ferrari university of parma

C# Generics. Object Oriented Programming (236703) Winter

#Students per correct answers

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

Photo credit: Andrew Kennedy JAVA GENERICS

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

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

3. Subtyping and Parametric Types

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Overloading, Type Classes, and Algebraic Datatypes

JAVA V Assertions Java, winter semester

Harvard School of Engineering and Applied Sciences Computer Science 152

Java Generics Java, summer semester

Typing issues JAVA GENERICS. ! Parametric Polimorphism. ! Bounded Polymorphism. ! F- Bounded Polymorphism 10/28/13. Examples and Problems

JAVA V Source files Java, winter semester

Comp215: Thinking Generically

Compiler Construction 2016/2017 Polymorphic Types and Generics

Outline of lecture. i219 Software Design Methodology 6. Object oriented programming language 3. Kazuhiro Ogata (JAIST)

1.1. Annotations History Lesson - C/C++

Subtyping for behaviour?

Refactoring Java Generics by Inferring Wildcards, In Practice

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

Advances in Programming Languages: Type accuracy

A Type-Passing Approach for the Implementation of Parametric Methods in Java

Advances in Programming Languages

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

Lecture 13: Subtyping

COMP6700/2140 Generic Methods

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

CSE Programming Languages Final exam - Spring Answer Key

Programming Languages Lecture 15: Recursive Types & Subtyping

CS108, Stanford Handout #8. Java Generics

Compiler Construction 2009/2010 Polymorphic Types and Generics

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

Taming the Wildcards

Polymorphic (Generic) Programming in Java

Generics method and class definitions which involve type parameters.

Java 5 New Language Features

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

Generics, I/O & Regular Expressions Maria Zontak

COSE212: Programming Languages. Lecture 3 Functional Programming in OCaml

Parametric types. map: ( a (a b) a list b list. filter: ( a bool) a list a list. Why? a and b are type variables!

Exercise 9 Parametric Polymorphism and Information Hiding November 24, 2017

Introducing Generics

Extending Programming Languages: the case of Java. Mirko Viroli DEIS, Alma Mater Studiorum Università di Bologna

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007

Outline. More optimizations for our interpreter. Types for objects

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

CS 520 Theory and Practice of Software Engineering Fall 2018

Harvard School of Engineering and Applied Sciences CS 152: Programming Languages

Type Checking and Type Inference

Tradeoffs. CSE 505: Programming Languages. Lecture 15 Subtyping. Where shall we add useful completeness? Where shall we add completeness?

Exam 2. Topics. Preconditions vs. Exceptions. Exam 2 Review. Exam 2 on Thursday, March 29 th. Closed book, closed computer, closed phone

Subtyping. Lecture 13 CS 565 3/27/06

The list abstract data type defined a number of operations that all list-like objects ought to implement:

Generics with Type Bounds

CSE Programming Languages Final exam - Winter Answer Key

Java Wildcards Meet Definition-Site Variance

Parametric types. aka: what s up with those a???

INSTRUCTIONS TO CANDIDATES

Types. What is a type?

6. Parametric Types and Virtual Types

Transcription:

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 OO languages support subtype polymorphism A variable can contain an instance of a subtype of the declared type Number x; x = new Integer(17); x = new Float(2.718);

4 Parametric polymorphism Allow code to be parametrized on types Introduce type variables or type parameters class Pair<A,B> { A fst; B snd; } Different languages allow one to parametrize classes, interfaces, methods, functions, expressions

In functional languages Can parametrize algebraic data types: datatype 'a list = nil cons of 'a * 'a list val xs: int list = cons(1, cons(2, nil)) More on this later in the course.

Parametric polymorphism in OO Many OO languages support parametrized classes, interfaces, and methods Called generics Issues: What can be parametrized? What types can be used to instantiate a type variable? Bounded polymorphism Variance Implementation

Templates C++ supports templates Similar to generics, but very different semantics and implementation Will discuss later

8 Types parametrized on types Can parametrize classes and interfaces/traits: class Pair<A,B> { A fst; B snd; } Can parametrize methods: <A> boolean equal(pair<a,a> p) { } return p.fst == p.snd;

Instantiation Type parameters are instantiated on other types. As if substitution was performed: Consider: class Pair<A,B> { A fst; B snd; } Pair<String,Integer> is as if had written PairSI with the class declaration: class PairSI { String fst; Integer snd; }

Instantiation What types can a parameter be instantiated upon? Java: Any reference type (<: java.lang.object) Scala: Any type C#: Any type

Bounded polymorphism Type parameters can be bounded when declared Subtype bounds: Java: interface Comparable<T extends Comparable<T>> {...} Scala: def max[a <: Ordered[A]](a: A, b: A) = if (a < b) b else a Structural bounds: PolyJ: class SortedList[T] where T { int compareto(t) } {...} 11

Variance What is the relationship between List[Integer] and List[Number]? Should List[Integer] be a subtype of List [Number]? For C[X]: X is a covariant parameter of C if C[A] <: C[B] when A <: B X is a contravariant parameter of C if C[A] <: C[B] when B <: A

13 Covariant parameters Suppose List[Integer] <: List[Number] ints: List[Integer] = new List[Integer](); ints.add(new Integer(23)); nums: List[Number] = ints; x: Number = ints.get(0); What about nums.add?

Covariant parameters Suppose List[Integer] <: List[Number] ints: List[Integer] = new List[Integer](); ints.add(new Integer(23)); nums: List[Number] = ints; x: Number = ints.get(0); nums.add(new Float(56.78));

Covariant parameters Cannot call methods that take a covariant parameter as an argument. A type system that allows this (without a run-time check) is does not enforce type safety.

16 Covariant parameters In Java, why is List<Integer> not a subtype of List<Number>? What happens if we substitute Integer and Number for A in List<A>? class List<Integer> { Integer get(int i) {...} void add(integer v) {...} } class List<Number> { Number get(int i) {...} void add(number v) {...} }

17 Covariant parameters Why is List<Integer> not a subtype of List<Number>? What happens if we substitute Integer and Number for A in List<A>? class List<Integer> { class List<Number> { Integer get(int i) {...} Number get(int i) {...} void add(integer v) {...} void add(number v) {...} } } Covariant method parameters

Covariant parameters Scala declares variance at the definition: class List[+A] {...} A is a covariant parameter of List The compiler checks that a covariant parameter does not occur as a method parameter type. => List.add(A) is not allowed.

Wildcards Java declares variance at the use: class List<A> {...} new List<? extends A>() These are called wildcards.

Covariant wildcards class List<A> {...} List<? extends Number> alist; List<Integer> ilist =...; alist = flist; List<Float> flist =...; alist = ilist; The type of each element of alist is some statically unknown subtype of Number

Covariant wildcards class List<A> {...} List<? extends Number> alist; List<Integer> ilist =...; alist = flist; List<Float> flist =...; alist = ilist; Compiler knows that the type parameter is some subtype of Number, but doesn t know which subtype!

Covariant wildcards class List<A> {...} List<? extends Number> alist; List<Integer> ilist =...; alist = flist; List<Float> flist =...; alist = ilist; Cannot call methods that take an A, e.g., add

Contravariant wildcards class List<A> {...} List<? super Float> alist; List<Object> olist =...; alist = olist; The type of each element of alist is some statically unknown supertype of Float

Contravariant wildcards class List<A> {...} List<? super Float> alist; List<Object> olist =...; alist = olist; Compiler knows that the type parameter is some supertype of Float, but doesn t know which one!

Contravariant wildcards class List<A> {...} List<? super Float> alist; List<Object> olist =...; alist = olist; Must assume methods that return an A, e.g., get, return Object.

26 Wildcard usability Want a list of Birds Should one declare a variable as: List<Bird>? List<? extends Bird>? List<? super Bird>? Hard to know which to do.

27 Wildcard usability List<Bird> birds Cannot do: birds = new List<Penguin>(); Can do: birds = new List<Bird>(); birds.add(new Bird()); birds.add(new Penguin()); Bird b = birds.get(0);

28 Wildcard usability List<? extends Bird> birds Can do: birds = new List<Penguin>(); Bird b = birds.get(0); Cannot do: birds = new List<Object>(); birds.add(new Bird()); birds.add(new Penguin());

29 Wildcard usability List<? super Bird> birds Can do: birds = new List<Object>(); birds.add(new Bird()); birds.add(new Penguin()); Object o = birds.get(0); Cannot do: birds = new List<Penguin>(); Bird b = birds.get(0);

Variance in Scala Scala declares variance at the class definition: class Map[-K,+V] {...} Contravariant in K Can use V in return types Covariant in V Can use K in argument types

Variance in C# C# does not support variant parameters. Why?

Variance in C# C# does not support variant parameters. Why? Simplifies the language.

Implementation Two main approaches: Polymorphic translation Template instantiation

Polymorphic translation Translate a parametrized class into a non-parametrized class Insert casts as needed class C<T> { } T x; class C { } Object x; C<String> c = new C<String> (); c.x = abc ; C c = new C(); c.x = abc ; String s = (String) c.x;

Template instantiation Create a new copy of the parametrized class for every instantiation Can be done at compile-time or at run-time. class C<T> { } T x; class C$S { } String x; C<String> c = new C<String>(); c.x = abc ; String s = c.x; C$S c = new C$S(); c.x = abc ; String s = c.x;

Comparison Polymorphic translation usually simpler to implement much less space overhead Java does this Template instantiation can generate code specialized to the type argument C# does this (at run-time) Scala does both: polymorphic translation for reference types template instantiation for primitives

C++ templates Do template instantiation on the source code With generics, type-checking of parametrized class done before instantiation With templates, type-checking does after instantiation C++ compiler needs source code of parametrized classes to instantiate them No separate compilation when templates used. Instantiation can fail with bizarre errors.

C# CLR generics implemented as run-time template instantiation Can be done directly by.net bytecode. No source required. C# compiler checks parametrized code so instantiation should never fail.

Type erasure Java erases type arguments from the translation This was done to support backward compatibility with older Java code: Code that uses Vector can still use Vector<T>

Erasure and run-time types Since types are erased, cannot be used for run-time type checking Cannot do: x instanceof List<Integer> Can only do: x instanceof List

Erasure and run-time types Casts are unchecked. List<Integer> xs = (List<Integer>) (List) new List<String>(); succeeds! Integer i = xs.get(0); fails with a ClassCastException Translated to: Integer i = (Integer) xs.get(0);

Erasure and variance Because types are erased, can side-step variance issues: List<Number> xs = new List<Integer>(); // illegal! List<Number> ys = (List) new List<Integer>(); // ok! Unchecked cast to List will always succeed. But not also: List<Number> ys = (List) new List<String>(); // ok! 42

Summary Parameterized types let you reuse code at multiple types Found in most modern statically typed languages Issues: What can be parametrized? What types can one instantiate a parameter with? Variance and bounds Implementation: polymorphic or templates