Search code examples
scalabuilt-in-types

Why no partial function type literal?


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?


Solution

  • 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.