Scala 中的可交换特征
我想定义一个具有两个值 x,y 的 Swappable
特征和一个 swap
方法,以便调用 swap
从 Swappable
继承的对象返回相同类型的另一个对象,但 x,y
已切换。到目前为止我最好的是:
trait Swappable[T] {
val x: T
val y: T
def swap: Swappable[T] = {
val (a,b) = (x,y)
new Swappable[T] { val x=b; val y=a }
}
}
但这不是我想要的,因为交换的返回类型是一些匿名类,而不是我开始使用的原始类,所以我收到如下错误:
def direct[S<:Swappable[Int]](s: S): S = if (s.x > s.y) s else s.swap
<console>:32: error: type mismatch;
found : Swappable[Int]
required: S
def direct[S<:Swappable[Int]](s: S): S = if (s.x > s.y) s else s.swap
^
是否可以做我正在尝试的事情做什么?交换的正确类型签名是什么?
I want to define a Swappable
trait with two values x,y
and a swap
method such that calling swap
on an object inheriting from Swappable
returns another object of the same type with x,y
switched. My best so far is:
trait Swappable[T] {
val x: T
val y: T
def swap: Swappable[T] = {
val (a,b) = (x,y)
new Swappable[T] { val x=b; val y=a }
}
}
But this isn't what I want because the return type of swap is some anonymous class, instead of the original class I started with, so I get errors like:
def direct[S<:Swappable[Int]](s: S): S = if (s.x > s.y) s else s.swap
<console>:32: error: type mismatch;
found : Swappable[Int]
required: S
def direct[S<:Swappable[Int]](s: S): S = if (s.x > s.y) s else s.swap
^
Is it possible to do what I'm trying to do? What is the correct type signature for swap?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不知道该怎么做,但我认为这可能有助于更好地了解您到底想要发生什么。考虑像 Now 这样的类
,如果您有
f = Foo(1, 2)
,f.swap
应该给您一个Foo
,其中x!=z
?如果是这样,Scala 中就没有办法创建这样的Foo
。如果不是,“交换 x 和 y”的真正含义是什么?也许您真正想要的是这样的:
但我不确定。
I don't know how to do it, but I think maybe it would help to get a better idea of what exactly you want to happen. Consider a class like
Now, if you have
f = Foo(1, 2)
, shouldf.swap
give you aFoo
wherex != z
? If so, there's no way within Scala to create aFoo
like that. If not, what does it really mean to "swap x and y"?Perhaps what you're really looking for is something like this:
But I'm not sure.
类似这样的事情怎么样:
What about something like that: