集合结构类型参数怪异
Collection structural type parameter weirdness
这看起来很简单,但我看不懂...
这样编译:
object CanFoo1 {
def foo(): Unit = {
println("Yup, I can foo alright")
}
}
object CanFoo2 {
def foo(): Unit = {
println("And I can foo with the best")
}
}
trait A {
type CanFoo = { def foo(): Unit }
def fooers: Seq[CanFoo]
}
class B extends A {
def fooers = Seq(
// CanFoo1, // <- won't compile when this is uncommented
CanFoo2
)
}
但是取消注释 // CanFoo1,
行给出:
error: type mismatch;
found : Seq[Object]
required: Seq[B.this.CanFoo]
(which expands to) Seq[AnyRef{def foo(): Unit}]
def fooers = Seq(
^
one error found
所以编译器似乎理解只包含一个元素 Seq(CanFoo2)
(或 Seq(CanFoo1)
)的集合是正确的类型,但是当两个对象都在集合中时它放弃了吗?我在这里做错了什么?
So it seems like the compiler understands that a collection containing
just one element Seq(CanFoo2)
(or Seq(CanFoo1)
) is of the correct
type, but when both objects are in the collection it gives up? What am
I doing wrong here?
当您将 CanFoo1
或 CanFoo2
传递给 Seq
应用程序时,序列被推断为分别为 CanFoo1.type
或 CanFoo2.type
类型,它未被推断为 CanFoo
.
类型
当您将两个元素都传递给 Seq
时,编译器会尝试寻找可以有效推断为使代码编译的通用类型,而它唯一可以找到的类型是 Object
,但是 fooers
据说是 Seq[CanFoo]
类型,所以编译器会大喊
您可以通过显式编写集合的类型来帮助编译器:
class B extends A {
def fooers = Seq[CanFoo](
CanFoo1,
CanFoo2
)
}
这看起来很简单,但我看不懂...
这样编译:
object CanFoo1 {
def foo(): Unit = {
println("Yup, I can foo alright")
}
}
object CanFoo2 {
def foo(): Unit = {
println("And I can foo with the best")
}
}
trait A {
type CanFoo = { def foo(): Unit }
def fooers: Seq[CanFoo]
}
class B extends A {
def fooers = Seq(
// CanFoo1, // <- won't compile when this is uncommented
CanFoo2
)
}
但是取消注释 // CanFoo1,
行给出:
error: type mismatch;
found : Seq[Object]
required: Seq[B.this.CanFoo]
(which expands to) Seq[AnyRef{def foo(): Unit}]
def fooers = Seq(
^
one error found
所以编译器似乎理解只包含一个元素 Seq(CanFoo2)
(或 Seq(CanFoo1)
)的集合是正确的类型,但是当两个对象都在集合中时它放弃了吗?我在这里做错了什么?
So it seems like the compiler understands that a collection containing just one element
Seq(CanFoo2)
(orSeq(CanFoo1)
) is of the correct type, but when both objects are in the collection it gives up? What am I doing wrong here?
当您将 CanFoo1
或 CanFoo2
传递给 Seq
应用程序时,序列被推断为分别为 CanFoo1.type
或 CanFoo2.type
类型,它未被推断为 CanFoo
.
当您将两个元素都传递给 Seq
时,编译器会尝试寻找可以有效推断为使代码编译的通用类型,而它唯一可以找到的类型是 Object
,但是 fooers
据说是 Seq[CanFoo]
类型,所以编译器会大喊
您可以通过显式编写集合的类型来帮助编译器:
class B extends A {
def fooers = Seq[CanFoo](
CanFoo1,
CanFoo2
)
}