Partial Functions in Scala

前端 未结 3 1518
悲哀的现实
悲哀的现实 2021-02-20 07:19

I just wanted to clarify something about partially defined functions in Scala. I looked at the docs and it said the type of a partial function is PartialFunction[A,B]

3条回答
  •  囚心锁ツ
    2021-02-20 08:01

    In addition to other answers, if by "multiple accepted types" you mean that you want the same function accept e.g. String, Int and Boolean (and no other types), this is called "union types" and isn't supported in Scala currently (but is planned for the future, based on Dotty). The alternatives are:

    1. Use the least common supertype (Any for the above case). This is what orElse chains will do.
    2. Use a type like Either[String, Either[Int, Boolean]]. This is fine if you have two types, but becomes ugly quickly.
    3. Encode union types as negation of intersection types.

提交回复
热议问题