Scala 类型的上限和下限 [英] Upper and Lower bound on scala type
问题描述
考虑以下层次结构:
class C1
class C2 extends C1
class C3 extends C2
class C4 extends C3
我想编写一个只接受 C2
和 C3
类型的函数.为此,我想到了以下几点:
I want to write a function that just accepts types C2
and C3
. For that I thought of the following:
def f [C >: C3 <: C2](c :C) = 0
我希望有以下行为
f(new C1) //doesn't compile, ok
f(new C2) //compiles, ok
f(new C3) //compiles, ok
f(new C4) // !!! Compiles, and it shouldn't
问题是用 C4
调用它时,我不想允许,但编译器接受.我知道 C4 <: C2
是正确的,C4
可以看作是 C3
.但是当指定绑定 [C >: C3 <: C2]
时,我希望编译器找到一个同时尊重两个边界的 C
,而不是逐个.
The problem is when calling it with C4
, which I don't want to allow, but the compiler accepts. I understand that C4 <: C2
is correct and that C4
can be seen as a C3
. But when specifying the bound [C >: C3 <: C2]
, I would expect the compiler to find a C
that respects both bounds at the same time, not one by one.
问题是:有什么方法可以实现我想要的,如果没有,编译器是否试图避免与此不一致?
Question is : Is there any way to achieve what I want, and if not, is the compiler trying to avoid some inconsistency with this?
编辑:从答案中我意识到我的假设是错误的.C4
总是满足 C >: C3
,所以这两个界限确实得到尊重.我的用例的方法是 C3 <:<C
.
Edit: from the answers I realized that my presumption is wrong. C4
always fulfills C >: C3
, so both bounds are indeed respected. The way to go for my use case is C3 <:< C
.
推荐答案
静态上,是的.施加此约束非常简单:
Statically, yes. It's pretty simple to impose this constraint:
def f[C <: C2](c: C)(implicit ev: C3 <:< C) = 0
f(new C4)
现在无法编译.
问题是,可能无法在编译时禁止以下行为:
The problem is, it's probably not possible to prohibit the following behaviour at compile time:
val c: C3 = new C4
f(c)
这里的变量c
有静态类型C3
,它通过编译器的任何类型的检查,但它在运行时实际上是一个C4
.
Here variable c
has static type C3
, which passes any kind of typechecking by compiler, but it is actually a C4
at runtime.
在运行时,您当然可以使用反射或多态检查类型并抛出错误或返回 Failure(...)
或 None
At runtime you can of course check the type using reflection or polymorphism and throw errors or return Failure(...)
or None
这篇关于Scala 类型的上限和下限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!