scala – 如何编写使用泛型类型执行case语句的函数?
发布时间:2020-12-16 18:16:08 所属栏目:安全 来源:网络整理
导读:参见英文答案 How to pattern match on generic type in Scala?????????????????????????????????????4个 ???????????? How do I get around type erasure on Scala? Or,why can’t I get the type parameter of my collections????????????????????????????
参见英文答案 >
How to pattern match on generic type in Scala?????????????????????????????????????4个
>???????????? How do I get around type erasure on Scala? Or,why can’t I get the type parameter of my collections?????????????????????????????????????11个 我想写一个这样的函数: def genericCase[T]() : PartialFunction[Any,T] = { case Wrapper(_,item: T) => item case Wrapper(item: T,_) => item } 总之,我想要一种方法来重用不同类型的模式匹配结构. 解决方法
您只需添加一个隐式ClassTag,它允许匹配泛型类:
import scala.reflect.ClassTag def genericCase[T: ClassTag]() : PartialFunction[Any,T] = { case Wrapper(_,item: T) => item case Wrapper(item: T,_) => item } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |