Skip to content

Instantly share code, notes, and snippets.

@bjornharrtell
Created August 29, 2012 19:37
Show Gist options
  • Save bjornharrtell/3517707 to your computer and use it in GitHub Desktop.
Save bjornharrtell/3517707 to your computer and use it in GitHub Desktop.
cannot compile because cannot override mutable variable
// cannot compile because cannot override mutable variable
// purpose of this pattern is to reuse logic from Base in Sub that works with BaseElements while Sub contains logic that works with SubElements
// not allowing override of vals has valid reasons so I'm looking for other options on how to design this
class BaseElement {
def foo() { println("I like foo") }
}
class SubElement extends BaseElement {
def bar() { println("I like bar") }
}
trait Base {
var map = Map[Int, BaseElement]()
// 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 {
override var map = Map[Int, SubElement]()
// want to be able to call methods on SubElement without having to upcast
map.get(0).get.bar();
}
@bjornharrtell
Copy link
Author

One ugly workaround would be to just skip the override and cast BaseElement to SubElement... but hey, it's ugly so it doesn't count.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment