【发布时间】:2014-05-05 04:34:11
【问题描述】:
我看到了问题的答案:Can all usages of forSome be replaced by an equivalent usage of _?,
但不明白不能使用“_”代替“forSome”的真实情况是什么。
我在Programming in Scala 书中读到:
存在类型是该语言完全支持的部分,但在 实践它们主要用于从 Scala 访问 Java 类型时。 我创建了 Scala 项目并引用了 Java 之一:
斯卡拉:
object Main {
def main(args: Array[String]): Unit = {
type Test = java.util.Collection[T] forSome { type T }
val contents: Test = (new Wild).contents
type Test2 = java.util.Collection[_]
val contents2: Test2 = (new Wild).contents
// foo((new Wild).contents2) // won't compile
foo1((new Wild).contents2)
foo1((new Wild).contents3)
foo2((new Wild).contents3)
}
def foo(xs: java.util.Map[T, T] forSome { type T }) {}
def foo1(xs: java.util.Map[_, _]) {}
def foo2(xs: java.util.Map[_, _ <: java.lang.Number]) {}
}
Java:
public class Wild {
public Collection<?> contents() {
return null;
}
public Map<?, ?> contents2() {
return null;
}
public Map<?, ? extends Number> contents3() {
return null;
}
}
在所有情况下,我都能将“forSome”替换为“_”。 那么需要“forSome”的真实案例是什么?请提供简单的工作示例。
【问题讨论】:
标签: scala