Skip to content

Instantly share code, notes, and snippets.

@arturaz
Created November 18, 2012 17:06
Show Gist options
  • Save arturaz/4106261 to your computer and use it in GitHub Desktop.
Save arturaz/4106261 to your computer and use it in GitHub Desktop.
class Foo { def hi = "Hello from Foo!" }
class Bar extends Foo { override def hi = "Hello from Bar!" }
abstract class Consumer {
type R <: Foo // abstract type R that is Foo or extends Foo
def greet(foo: R) = foo.hi // method "greet" with 1 arg "foo" of type R, calls and returns foo.hi
}
class FooConsumer extends Consumer {
type R = Foo // Concretize type R to Foo.
}
class BarConsumer extends Consumer {
type R = Bar // Only accept Bar, not Foo.
}
// Works.
println(new FooConsumer().greet(new Foo))
println(new FooConsumer().greet(new Bar))
println(new BarConsumer().greet(new Bar))
// Does not compile.
// /home/arturas/types.scala:22: error: type mismatch;
// found : this.Foo
// required: this.Bar
println(new BarConsumer().greet(new Foo))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment