user3663882 user3663882 - 1 year ago 96
Scala Question

Why does scala compiler allow invocation of PartialFunction without arguments?

I was kind of disappointed by the fact that scala compiler allows to compile this pretty wierd, obviously mistaken code:

val foo: PartialFunction[Any, Unit] = {
case s: String => println(s)

and instead of printing compile-error, it throws

Exception in thread "main" scala.MatchError: () (of class scala.runtime.BoxedUnit)

What was the reason for that?

Answer Source

In your case your partial function takes an Any argument, and that includes Unit (since unit is a subtype of Any - Any -> AnyVal -> Unit). Calling apply() on that is equal to calling apply(()).

If you have a partial function which doesn't accept Unit you get an error indicating that the argument for apply is missing:

scala> val foo : PartialFunction[AnyRef, Unit] = {
     | case arg => println(s"arg = $arg")
     | }
foo: PartialFunction[AnyRef,Unit] = <function1>

scala> foo()
<console>:13: error: not enough arguments for method apply: (v1: AnyRef)Unit in trait Function1.
Unspecified value parameter v1.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download