Skip to content

Instantly share code, notes, and snippets.

@johansjoberg
Created August 31, 2012 19:11
Show Gist options
  • Save johansjoberg/3557577 to your computer and use it in GitHub Desktop.
Save johansjoberg/3557577 to your computer and use it in GitHub Desktop.
Possible solution for GIST 3517707 on url https://gist.github.com/3517707 Uses abstract types and overrides the type in the subclass
class BaseElement {
def foo() { println("I like foo") }
}
class SubElement extends BaseElement {
def bar() { println("I like bar") }
}
trait Base {
//Abstract type T must be BaseElement or a subclass of BaseElement
type T <: BaseElement
var map = Map[Int, T]()
// want to provide default impl for Sub (without depending on SubElement)
map.get(0).get.foo()
// want to be able to mutate Base (Map is immutable for thread safety so need to replace it)
map = map -- map.keys.filter(_>0)
}
class Sub extends Base {
//overriding the type T seem to only work if the type specified as an override satisfies the requirement of
// the parent type. Changing this to String will fail to compile.
override type T = SubElement
// want to be able to call methods on SubElement without having to upcast
map.get(0).get.bar()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment