我有以下设置:
class Test[A](function: A => String) {
def process(data: Any) { //has to be Any since it is user IO
if (data of Type A)
function(data)
}
}
我似乎无法让类型检查工作。我尝试将一个隐式TypeTag添加到Test [A],但无法从过程中访问它。是否可以在过程函数中与Test的类型参数进行匹配?
为此,请使用ClassTag
和match
:
import scala.reflect.ClassTag
class Test[A : ClassTag](function: A => String) {
def process(data: Any) { //has to be Any since it is user IO
data match {
case data: A => function(data)
case _ =>
}
}
}
由于ClassTag
范围的隐式,即使可以通用,match
也可以区分A
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句