在Scala中泛型类型的模式匹配 [英] Pattern matching on generic type in Scala

查看:219
本文介绍了在Scala中泛型类型的模式匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



现在,根据T的类型(在我的情况下,它可以是 Double 布尔值 LocalDate ),
我需要在 OB 。像这样的东西(我知道代码没有意义,但我想传达我的意思):

  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]
}
}



考虑到Scala的擦除属性,反射可以以某种方式用来完成工作吗?它甚至有可能吗?

解决方案

如果您使用2.10以上版本,我会使用TypeTag

  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

另请参阅这个冗长但很棒的答案



还要注意,我只是瞥了一眼scala反射,所以有人可能会写一个更好的TypeTag使用示例。


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?

解决方案

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.

这篇关于在Scala中泛型类型的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆