【发布时间】:2016-10-14 19:56:07
【问题描述】:
class Queue[+T](
private val leading: List[T],
private val trailing: List[T]
) {
def append[U >: T](x: U) =
new Queue[U](leading, x :: trailing) // ...
}
class Fruit
class oranges extends Fruit
class apple extends Fruit
class diffAppale
val q1: Queue[Fruit] = new Queue[apple](List(new apple), List())
//> q1 : Test.Queue[Test.Fruit] = Test$Queue@30c7da1e
q1.append(new Fruit)
//> res0: Test.Queue[Test.Fruit] = Test$Queue@506e6d5e
q1.append(new oranges)
//> res1: Test.Queue[Test.Fruit] = Test$Queue@96532d6
q1.append(new diffAppale) // i want to restrict this
//> res2: Test.Queue[Object] = Test$Queue@3796751b
在这里我可以添加任何对象我可以添加到附加函数,我可以看到结果类型被降级为最低公分母
但我想拥有与 java 相同的行为,比如 def append[? super T](x: U) // 这里的 append 函数将获取所有属于 T 超类型的对象,我如何在 scala 中实现类似的对象(实现 super 并为 java 等泛型扩展)
【问题讨论】:
-
为什么这对你来说是个问题?
-
我想只通过append函数添加一些特定的对象类型,可以通过>:,
-
我认为您正在尝试考虑更复杂的需要。如果您在特定情况下所需的返回类型是
Queue[Fruit],无论如何它都不允许您返回Queue[Any]。大多数时候,当程序正确地进行类型检查时,人为地强制执行额外的类型约束是没有意义的。无论如何,正如我在答案中建议的那样,如果你真的想要这个,只需删除差异。