scala 中的匹配类型
Scala 中可以匹配类型吗?像这样的东西:(
def apply[T] = T match {
case String => "you gave me a String",
case Array => "you gave me an Array"
case _ => "I don't know what type that is!"
}
但是显然可以编译:))
或者也许正确的方法是类型重载......这可能吗?
不幸的是,我无法向它传递对象的实例和模式匹配。
Is it possible to match types in Scala? Something like this:
def apply[T] = T match {
case String => "you gave me a String",
case Array => "you gave me an Array"
case _ => "I don't know what type that is!"
}
(But that compiles, obviously :))
Or perhaps the right approach is type overloading…is that possible?
I cannot pass it an instance of an object and pattern match on that, unfortunately.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用清单并对其进行模式匹配。不过,传递数组类的情况是有问题的,因为 JVM 对每种数组类型使用不同的类。要解决此问题,您可以检查有问题的类型是否已删除到数组类中:
You can use manifests and do a pattern match on them. The case when passing an array class is problematic though, as the JVM uses a different class for each array type. To work around this issue you can check if the type in question is erased to an array class:
Manifest
id 已弃用。但您可以使用TypeTag
希望这会有所帮助。
Manifest
id deprecated. But you can useTypeTag
Hope this helps.