During the week, I ended up trying a syntax for defining a partial function that didn’t please the compiler. I found the workaround, but was left thinking maybe the thing I intuitively tried would make sense.
So I’d like to hear your replies on this. It has to do with the difference (or lack thereof) between normal and partial functions.
In short, this does not compile (on Scala 2.12.6):
scala> def pf: String = { case 0 => "zero" }
I found the workaround (using val
and PartialFunction[Any,String]
), but the point is. Why shouldn’t this work?
The use case is wanting to define a partial function, with an explicitly defined return type (but leaving the possible argument types to be deduced from the cases. In my case, I needed to use the pf twice, which is why anonymous pf wasn’t enough.
What I do like about this, is that use of def
(currently not used for partial functions, I think) brings the partial functions closer to normal functions, in the programmer’s mental model. They are anyways connected. One can pass either one to many methods (map, collect, …) and one can ‘.lift’ a partial function to be a fully defined one.
What do you think?
I’ve programmed in Scala for years without needing this, so it’s not a major deficiency. But maybe also the inverse is true: since there’s no easy way to name a partial function, we rarely name them.