How to define “type disjunction” (union types)?

前端 未结 15 2215
温柔的废话
温柔的废话 2020-11-22 05:52

One way that has been suggested to deal with double definitions of overloaded methods is to replace overloading with pattern matching:

object Bar {
   def fo         


        
15条回答
  •  盖世英雄少女心
    2020-11-22 06:42

    Adding to the already great answers here. Here's a gist that builds on Miles Sabin union types (and Josh's ideas) but also makes them recursively defined, so you can have >2 types in the union (def foo[A : UNil Or Int Or String Or List[String])

    https://gist.github.com/aishfenton/2bb3bfa12e0321acfc904a71dda9bfbb

    NB: I should add that after playing around with the above for a project, I ended up going back to plain-old-sum-types (i.e. sealed trait with subclasses). Miles Sabin union types are great for restricting the type parameter, but if you need to return a union type then it doesn't offer much.

提交回复
热议问题