> val foo: PartialFunction[String, Unit] = { case i: String => }
foo: PartialFunction[String,Unit] = <function1>
> val bar: PartialFunction[Int, Unit] = { case i: Int => }
bar: PartialFunction[Int,Unit] = <function1>
> foo orElse bar
PartialFunction[String with Int,Unit] = <function1>
What is String with Int?
. I don't think that's even possible.
> (foo orElse bar)(new String with Int)
error: illegal inheritance from final class String
(foo orElse bar)(new String with Int)
^
error: class Int needs to be a trait to be mixed in
(foo orElse bar)(new String with Int)
^
Shouldn't it be PartialFunction[Nothing,Unit]
?
What is String with Int?
It's an intersection type. I.e. a value of this type must be an Int
and a String
simultaneously.
I don't think that's even possible.
Yes, this is an uninhabited type. However, in general if you replace Int
and String
with some types A
and B
, you'll get PartialFunction[A with B, Unit]
and the compiler doesn't have a special case for this.
Well, as said before, it's a compound type, and it works for any two types (classes, traits), as in the following code:
class B
class C extends B
class D extends C
val bf: PartialFunction[B, Unit] = {case b: B => println("some b") }
val cf: PartialFunction[C, Unit] = {case c: C => println("some c") }
val g = bf orElse cf
g(new D) // some b
It's just that sometimes it lacks of sense in some contexts. These links may prove useful:
http://www.scala-lang.org/old/node/110
http://www.scala-lang.org/files/archive/spec/2.11/03-types.html#compound-types
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With