The problem is that the type of the left-hand side of the orElse
is inadequately specified by the return type of the method given that the right-hand side exists. (Also, the LHS is not by syntax necessarily a partial function; it may be an incompletely specified Function1
.) Since even conceptually the compiler can't really do the right thing without a bit of extra help here, you're going to have to do something.
So the only question left is whether there is a better way than : Respond
to indicate the type of the left-hand side. It turns out that the answer is maybe:
implicit class Resp(val underlying: Respond) extends AnyVal {
def or(r: Respond) = underlying orElse r
}
abstract class A { def respond: Respond = Map.empty }
class B extends A {
override def respond = Resp{ case "A" => "The letter A" } or super.respond
}
Thanks to the use of implicit value classes, there's essentially no overhead for doing it this way. The cost is that you have a custom mini-DSL instead of vanilla Scala library calls.