Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

Pattern matching on generic type in Scala

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), I need to apply functions on ob. Something like this (I know the code will make no sense but I am trying to convey what I mean to do):

def X[T](ob: Observable[T]): Observable[T] = {
    //code  
    T match {
    case Double => DoSomething1(ob:Observable[Double]):Observable[Double]
    case Boolean => DoSomething2(ob:Observable[Boolean]):Observable[Boolean]
    case LocalDate => DoSomething3(ob:Observable[LocalDate]):Observable[LocalDate]
    }
}

Taking into consideration the Erasure property of Scala, can reflection be somehow used to get the job done? Is it even possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...