我找到了以下代码片段:
List[T] forSome { type T }
Run Code Online (Sandbox Code Playgroud)
在forSome看起来像一个方法,但我的朋友告诉我,这是一个关键字.
我用Google搜索了一下,但发现的文件很少forSome.它是什么意思,我在哪里可以获得一些文件?
我在scala中遇到以下层次结构的问题:
class ScalaGenericTest {
def getValue[A, B <: Abstract[A]](clazz: B): A = clazz.a
def call: String = {
val sub: Subclass = new Subclass
getValue(sub)
}
}
class Subclass extends Abstract[String] {
def a: String = "STRING"
}
abstract class Abstract[A] {
def a: A
}
Run Code Online (Sandbox Code Playgroud)
编译器似乎无法在对getValue函数的调用中绑定泛型参数A - 我认为它应该能够从Subclass的定义中推断出这一点.编译错误如下:
推断类型参数[Nothing,Subclass]不符合方法getValue的类型参数bounds [A,B <:Abstract [A]]
如果我明确地将泛型类型参数传递给方法,它可以工作,getValue[String,Subclass](sub)但是肯定编译器应该能够推断出这个吗?
相同的层次结构在Java中运行良好:
public class JavaGenericTest {
public <T,U extends Abstract<T>> T getValue(U subclass) {
return subclass.getT();
}
public String call(){
Subclass sub = new Subclass(); …Run Code Online (Sandbox Code Playgroud) 我想创建一个可变的协变类,所以我需要在setter方法中添加一个较低的类型绑定.但是我也想让setter方法设置一个字段,所以我猜这个字段需要绑定相同的类型?
class Thing[+F](initialValue: F) {
private[this] var secondValue: Option[G >: F] = None
def setSecondValue[G >: F](v: G) = {
this.secondValue = Some(v)
}
}
Run Code Online (Sandbox Code Playgroud)
该方法编译得很好.但是名为secondValue的字段根本不编译,错误消息如下:
Multiple markers at this line
- ']' expected but '>:' found.
- not found: type G
Run Code Online (Sandbox Code Playgroud)
我需要做什么?
根据这个问题的答案,似乎在类型定义的一个组件之后放置"forSome"不同于将它放在整个事件的末尾.例如,似乎以下内容之间存在差异:
def one: Foo[U >: T] forSome {type U >: T}
def one: Foo[U forSome {type U >: T}]
Run Code Online (Sandbox Code Playgroud)
Scala语言规范似乎没有说明差异,我想象将量词转移到外部没有任何区别.如果它确实有所作为,我会认为它将如本答案所述,基本上说Set [X forSome {type X}]允许X在set元素之间变化,其中Set [X] forSome {type X}才不是.但是,这似乎不是整个故事和/或不正确,因为这不编译:
trait Bar {
def test: Set[X] forSome {type X}
}
def test(b: Bar) {
val set = b.test
val h = set.head
set.contains(h)
}
Run Code Online (Sandbox Code Playgroud)
但这样做:
trait Bar {
def test: Set[X forSome {type X}]
}
def test(b: Bar) {
val set = b.test
val h = set.head
set.contains(h) …Run Code Online (Sandbox Code Playgroud)