如何检查值的可见类型
我有这样的事情:
def my_check[T](arg: T) = arg match {
case x: GenTraversable[_] = ... // XX
case x: Array[_]
...
我想合并一些 cases
表达式:
在上面标有 XX 的代码中,我想检查是否 arg <: GenTraversable[_]
或 arg <% GenTraversable[-]
。例如, Array 类型也可以匹配这种情况(存在从 Array 到 WrapperArray <: GenTraversable 的隐式转换)
我不知道不想在解决方案中使用异常,所以我对以下内容不感兴趣:
try:
val trv: GenTraversable = arg
catch ...
我在 my_check
函数中尝试过类似
T <:< GenTraversable // error: not found: value T
但编译器抱怨。
I have something like this:
def my_check[T](arg: T) = arg match {
case x: GenTraversable[_] = ... // XX
case x: Array[_]
...
I want to merge some cases
expression:
In the code above marked with XX, I want to check if arg <: GenTraversable[_]
or arg <% GenTraversable[-]
. For example, the Array
type could match this case as well (there exists implicit conversion from Array
to WrapperArray <: GenTraversable
)
I don't want to use exception in the solution, so I'm not interesting in something like:
try:
val trv: GenTraversable = arg
catch ...
I've tried in my_check
function something like
T <:< GenTraversable // error: not found: value T
But compiler complain.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
隐式解析(<% 包括)是编译时的事情,基于编译时已知的类型。
在您的例程中,编译时唯一知道的有关 arg 的信息是它的类型为
T
,这几乎什么都没有。您可能会遇到类似这样的情况,但是,只有在编译时已知
arg
是GenTraversable
时,您的例程才能被调用。我不知道你在哪里写了
T <:< GenTraversable[_]
(可能在需要值的地方)。要获得从类型A
到B
的隐式转换,您可以编写implicitly[A =>; B]
,但同样,如果在编译时无法解析,它将失败。所以这里没有任何帮助,因为T
是一个不受约束的泛型参数。Implicit resolution (<% included) is a compile time thing, based on the types as they are known at compile time.
In your routine, the only thing that is known at compile time about arg is that it is of type
T
, which is about nothing. You might have something such asThis is definitely not the same thing however your routine could only be called if
arg
is known at compile time to be aGenTraversable
.I don't know where you wrote
T <:< GenTraversable[_]
(probably in a place where a value is expected). To get the implicit conversion from typesA
toB
, you can writeimplicitly[A => B]
, but again, it will fail if it cannot be resolved at compile time. So it would not be any help here, withT
an unconstrained generic parameter.我不确定我是否理解你的问题。这段代码对我有用:
如果 Y 是 X 的子类(如本例所示),那么您必须从 Y 开始,然后再采用更通用的类。请再次解释一下问题...?
I am not sure I understand your question. This code works for me:
If Y is a subclass of X (as in this case) then you must start with Y and take the more generic classes later on. Please explain the question once more...?
我很确定这是不可能的。模式匹配发生在运行时,隐式和非隐式之间的区别仅存在于编译时。
I am pretty sure this isn't possible. Pattern matching happens at runtime, and distinction between implicits and non-implicits only exists at complile-time.