Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "String with Int" supposed to mean?

> 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]?

like image 480
Paul Draper Avatar asked Feb 12 '23 12:02

Paul Draper


2 Answers

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.

like image 139
Alexey Romanov Avatar answered Feb 14 '23 01:02

Alexey Romanov


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

like image 27
ale64bit Avatar answered Feb 14 '23 00:02

ale64bit