Scala:检查对象是否为数字 [英] Scala: checking if an object is Numeric
问题描述
模式匹配是否有可能检测某些内容是否为 Numeric
?我想做以下事情:
Is it possible for a pattern match to detect if something is a Numeric
? I want to do the following:
class DoubleWrapper(value: Double) {
override def equals(o: Any): Boolean = o match {
case o: Numeric => value == o.toDouble
case _ => false
}
override def hashCode(): Int = value ##
}
但当然这并没有真正起作用,因为 Numeric
不是诸如 Int
和 Double
之类的超类型,它是一个类型类.我也不能做类似 def equals[N: Numeric](o: N)
的事情,因为 o
必须是 Any
以适应equals
的约定.
But of course this doesn't really work because Numeric
isn't the supertype of things like Int
and Double
, it's a typeclass. I also can't do something like def equals[N: Numeric](o: N)
because o
has to be Any
to fit the contract for equals
.
那么如何在不列出每个已知的 Numeric
类(包括我什至可能不知道的用户定义类)的情况下执行此操作?
So how do I do it without listing out every known Numeric
class (including, I guess, user-defined classes I may not even know about)?
推荐答案
原来的问题无法解决,我的理由如下:
The original problem is not solvable, and here is my reasoning why:
要查明一个类型是否是一个类型类的实例(比如Numeric),我们需要隐式解析.隐式解析在编译时完成,但我们需要在运行时完成.目前这是不可能的,因为据我所知,Scala 编译器不会在编译后的类文件中留下所有必要的信息.要看到这一点,可以使用包含局部变量的方法编写一个测试类,该变量具有隐式修饰符.移除修饰符后,编译输出不会改变.
To find out whether a type is an instance of a typeclass (such as Numeric), we need implicit resolution. Implicit resolution is done at compile time, but we would need it to be done at runtime. That is currently not possible, because as far as I can tell, the Scala compiler does not leave all necessary information in the compiled class file. To see that, one can write a test class with a method that contains a local variable, that has the implicit modifier. The compilation output will not change when the modifier is removed.
这篇关于Scala:检查对象是否为数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!