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

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

    A type class solution is probably the nicest way to go here, using implicits. This is similar to the monoid approach mentioned in the Odersky/Spoon/Venners book:

    abstract class NameOf[T] {
      def get : String
    }
    
    implicit object NameOfStr extends NameOf[String] {
      def get = "str"
    }
    
    implicit object NameOfInt extends NameOf[Int] {
     def get = "int"
    }
    
    def printNameOf[T](t:T)(implicit name : NameOf[T]) = println(name.get)
    

    If you then run this in the REPL:

    scala> printNameOf(1)
    int
    
    scala> printNameOf("sss")
    str
    
    scala> printNameOf(2.0f)
    :10: error: could not find implicit value for parameter nameOf: NameOf[
    Float]
           printNameOf(2.0f)
    
                  ^
    

提交回复
热议问题