SeqLike 中排序方法的签名
Signature of sorted method in SeqLike
我不明白 SeqLike
特征中 sorted
方法签名的目的:
def sorted[B >: A](implicit ord: Ordering[B]): Repr
更精确,我没听懂:
- 原因
B>:A
Repr
是什么意思?
也许你可以阐明这一点。
在此先感谢您的回答!
[B >: A]
表示 sorted
可以用 B 上的任何顺序调用,其中 B 是 A 的超类型。
我想A是trait本身的类型参数,即
SeqLike 定义为 SeqLike[A, This]
。详尽无遗,如SeqLike[A, +This <: SeqLike[A, This] with Seq[A]]
。 This <: SeqLike[A, This]
是 F 界多态性。
trait A[T <: A[T]] {} // the type parameter to A must be an A
class C extends A[C] {} // this is how you use it.
actual return type of SeqLike.sorted
是 This
。
这很有用,因为这允许 SeqLike 的方法不仅 return SeqLike
s,而且子类型!
回到前面的简单示例...
trait Model[T <: Model[T]] {
def find(id: Int): T = ...
}
class User extends Model[User]
val model: User = new User().find(3) # no need to cast.
- 该方法采用隐式
Ordering
,它应该能够处理 A
的某些 超类型 (因此 B >: A
)。 IE。您应该能够使用 Ordering[AnyVal]
来比较 Int
值(因为 AnyVal
是 Int
的超类型)。
Repr
是 SeqLike
特征本身 (SeqLike[+A, +Repr]
) 的类型参数,描述为 "the type of the actual collection containing the elements"。这是为了确保像 sorted
这样的方法将 return 相同类型的集合(例如 List.sorted
仍然是 List
)。
这里简单解释一下为什么B >: A
:
让我们考虑这个 class(不编译):
class C[+T] {
def m(x: T): T = x
}
+T
表示协变,即 C[Any]
是例如 class 的超class C[Int]
。现在("123"
是 String
,所以它也是 Any
):
val cInt: C[Any] = new C[Int]
cInt.m("123") // ??? We are supposed to return Int here
现实中:
class C[+T] {
def m[A >: T](x: A): A = x
}
so(编译器将A
推断为Any
和String
的最近共同祖先,即Any
)
val cInt: C[Any] = new C[Int]
cInt.m("123") // Any = 123
SeqLike
的定义:trait SeqLike[+A, +Repr]
,注意 +A
我不明白 SeqLike
特征中 sorted
方法签名的目的:
def sorted[B >: A](implicit ord: Ordering[B]): Repr
更精确,我没听懂:
- 原因
B>:A
Repr
是什么意思?
也许你可以阐明这一点。
在此先感谢您的回答!
[B >: A]
表示 sorted
可以用 B 上的任何顺序调用,其中 B 是 A 的超类型。
我想A是trait本身的类型参数,即
SeqLike 定义为 SeqLike[A, This]
。详尽无遗,如SeqLike[A, +This <: SeqLike[A, This] with Seq[A]]
。 This <: SeqLike[A, This]
是 F 界多态性。
trait A[T <: A[T]] {} // the type parameter to A must be an A
class C extends A[C] {} // this is how you use it.
actual return type of SeqLike.sorted
是 This
。
这很有用,因为这允许 SeqLike 的方法不仅 return SeqLike
s,而且子类型!
回到前面的简单示例...
trait Model[T <: Model[T]] {
def find(id: Int): T = ...
}
class User extends Model[User]
val model: User = new User().find(3) # no need to cast.
- 该方法采用隐式
Ordering
,它应该能够处理A
的某些 超类型 (因此B >: A
)。 IE。您应该能够使用Ordering[AnyVal]
来比较Int
值(因为AnyVal
是Int
的超类型)。 Repr
是SeqLike
特征本身 (SeqLike[+A, +Repr]
) 的类型参数,描述为 "the type of the actual collection containing the elements"。这是为了确保像sorted
这样的方法将 return 相同类型的集合(例如List.sorted
仍然是List
)。
这里简单解释一下为什么B >: A
:
让我们考虑这个 class(不编译):
class C[+T] {
def m(x: T): T = x
}
+T
表示协变,即 C[Any]
是例如 class 的超class C[Int]
。现在("123"
是 String
,所以它也是 Any
):
val cInt: C[Any] = new C[Int]
cInt.m("123") // ??? We are supposed to return Int here
现实中:
class C[+T] {
def m[A >: T](x: A): A = x
}
so(编译器将A
推断为Any
和String
的最近共同祖先,即Any
)
val cInt: C[Any] = new C[Int]
cInt.m("123") // Any = 123
SeqLike
的定义:trait SeqLike[+A, +Repr]
,注意 +A