Scala:两个相等类型之间的类型方差和模式匹配
前几天我正在玩一个类来处理一些算术运算(是的,我知道数字将在 2.8 中出现),并发现自己想知道如何简化以下内容:
def Foo[A]( _1:A, _2:A ) = (_1, _2) match{
case _1:Bar, _2:Bar => _1 + _2
case _1:Baff, _2:Baff => _1 push _2
case _, _ => None
}
这样我就可以做
def Foo[A]( _1:A, _2:A ) = _1 match{
case _1:Bar => _1 + _2
case _1:Baff => _1 push _2
case _ => None
}
当然,我知道在按照声明方式声明函数,_2
的类型可以继承自 _1
的类型,“A”可以是共享特征,等等。我知道这意味着编译器需要抗议以保护代码。有没有办法说“我希望 _1 和 _2 是同一个 extact 类”,这样我就不必进行双重 _1:Int, _2:int
声明?
I was playing around the other day with making a class to handle some arithmetic operations (yes, I know numeric is coming out in 2.8) and found myself wondering how to simplify the following:
def Foo[A]( _1:A, _2:A ) = (_1, _2) match{
case _1:Bar, _2:Bar => _1 + _2
case _1:Baff, _2:Baff => _1 push _2
case _, _ => None
}
so that I can do just
def Foo[A]( _1:A, _2:A ) = _1 match{
case _1:Bar => _1 + _2
case _1:Baff => _1 push _2
case _ => None
}
Granted, I know that in declaring the function the way it's been declared that _2
's type could conceivably inherit from _1
's type, "A" could be a shared trait, or so on. I know this means the compiler needs to protest to protect the code. Is there a way to say "I want _1 and _2 to be the same extact class" so that I don't have to make the double _1:Int, _2:int
declaration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会在这里使用重载。
I'd use overloading here instead.
也许我误解了你的意思,但如果你只是希望两个参数必须是相同的类型,你可以执行如下操作:
这指定
B
都是由B
限制的下限和上限类型code>A,因此必须是A
。因此,仅当_1
和_2
类型相同时才会编译。Perhaps Im misunderstanding you, but if you just want the two parameters to be required to be the same type, you can do something like the following:
This specifies that
B
is both lower and upper type bounded byA
, thus must beA
. Thus it will only compile if_1
and_2
are of the same type.