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

前端 未结 15 2224
温柔的废话
温柔的废话 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:35

    Here is the Rex Kerr way to encode union types. Straight and simple!

    scala> def f[A](a: A)(implicit ev: (Int with String) <:< A) = a match {
         |   case i: Int => i + 1
         |   case s: String => s.length
         | }
    f: [A](a: A)(implicit ev: <:<[Int with String,A])Int
    
    scala> f(3)
    res0: Int = 4
    
    scala> f("hello")
    res1: Int = 5
    
    scala> f(9.2)
    :9: error: Cannot prove that Int with String <:< Double.
           f(9.2)
            ^
    

    Source: Comment #27 under this excellent blog post by Miles Sabin which provides another way of encoding union types in Scala.

提交回复
热议问题