Pattern matching on generic type in Scala

前端 未结 1 578
醉梦人生
醉梦人生 2020-11-29 04:33

I have scala function that looks like this:

Now, depending upon the type of T (In my case, it can be Double, Boolean and LocalDate

相关标签:
1条回答
  • 2020-11-29 05:27

    I would go with TypeTag if you're on 2.10+

    import reflect.runtime.universe._
    
    class Observable[Foo]
    
    def X[T: TypeTag](ob: Observable[T]) = ob match {
        case x if typeOf[T] <:< typeOf[Double]   => println("Double obs")
        case x if typeOf[T] <:< typeOf[Boolean]  => println("Boolean obs")
        case x if typeOf[T] <:< typeOf[Int]      => println("Int obs")
    }
    
    X(new Observable[Int])
    // Int obs
    

    See also this lengthy, but awesome answer

    Note also that I only took a glimpse at scala reflection, so likely somebody may write a better example of TypeTag usage.

    0 讨论(0)
提交回复
热议问题