Why no partial function type literal?
Asked Answered
S

1

13

I wonder why there doesn't exist a literal for partial function types. I have to write

val pf: PartialFunction[Int, String] = {
  case 5 => "five"
}

where an literal like :=> would be shorter:

val pf: Int :=> String = {
  case 5 => "five"
}

Partial functions are often used and in Scala already some "special" feature, so why no special syntax for it?

Stubble answered 15/3, 2012 at 23:51 Comment(0)
U
20

Probably in part because you don't need a literal: you can always write your own :=> as a type infix operator if you want more concise syntax:

scala> type :=>[A, B] = PartialFunction[A, B]
defined type alias $colon$eq$greater

scala> val pf: Int :=> String = { case 5 => "five" }
pf: :=>[Int,String] = <function1>

scala> pf.isDefinedAt(0)
res0: Boolean = false

scala> pf.isDefinedAt(5)
res1: Boolean = true

I'm not one of the designers of the Scala language, though, so this is more or less a guess about the "why?". You might get better answers over at the scala-debate list, which is a more appropriate venue for language design questions.

Uriniferous answered 16/3, 2012 at 0:8 Comment(4)
+1 I was just going to suggest the type alias trick but didn't know it was possible to take a step further and use the infix form.Tuberous
@Vlad, I'll admit that I went through a (brief) type infix operator abuse phase when I first learned about them, and still think it's a pretty nifty little language feature.Uriniferous
I've asked the same before and the reason that it has not been added to the language (it existed briefly as ~>) is something to do with how type parameters are inferred l-2-rSoult
Once paulp added =>? to the library, but reversed that because the associativity is not the same as => (a keyword).Castillo

© 2022 - 2024 — McMap. All rights reserved.