Scala 中 toSet 的 return 类型是什么
What is the return type of toSet in Scala
假设我有一个 Int
的 Scala 数组 arr
。考虑 arr.toSet
。我知道 toSet
returns 一个 Set
对象。这是 Set
默认的 HashSet
还是 TreeSet
?
https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/immutable/Set.scala
最多 4 个元素 EmptySet
、Set1
、...、Set4
(如元组),然后是 HashSet
.
toSet
返回值的编译时类型是Set
def toSet[B >: A]: immutable.Set[B]
但是 toSet
返回的对象的运行时 class 可能不同,我们可以使用 Scala REPL
检查
Array(1).toSet.getClass // class immutable.Set$Set1
Array(1, 2).toSet.getClass // class immutable.Set$Set2
Array(1, 2, 3).toSet.getClass // class immutable.Set$Set3
Array(1, 2, 3, 4).toSet.getClass // class immutable.Set$Set4
Array(1, 2, 3, 4, 5).toSet.getClass // class immutable.HashSet
Array(1, 2, 3, 4, 5, 6).toSet.getClass // class immutable.HashSet
...
输出
Suppose I have a Scala array arr
of Int
. Consider arr.toSet
. I know that toSet
returns a Set
object. Is this Set
a HashSet
, or TreeSet
in default?
都没有。这是一个 scala.collection.immutable.Set
.
这里是 the documentation for scala.Array.toSet
(which is actually scala.collection.IterableOnceOps.toSet
):
def toSet[B >: A]: Set[B]
可以看到,明确指定了return类型为Set
。
假设我有一个 Int
的 Scala 数组 arr
。考虑 arr.toSet
。我知道 toSet
returns 一个 Set
对象。这是 Set
默认的 HashSet
还是 TreeSet
?
https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/immutable/Set.scala
最多 4 个元素 EmptySet
、Set1
、...、Set4
(如元组),然后是 HashSet
.
toSet
返回值的编译时类型是Set
def toSet[B >: A]: immutable.Set[B]
但是 toSet
返回的对象的运行时 class 可能不同,我们可以使用 Scala REPL
Array(1).toSet.getClass // class immutable.Set$Set1
Array(1, 2).toSet.getClass // class immutable.Set$Set2
Array(1, 2, 3).toSet.getClass // class immutable.Set$Set3
Array(1, 2, 3, 4).toSet.getClass // class immutable.Set$Set4
Array(1, 2, 3, 4, 5).toSet.getClass // class immutable.HashSet
Array(1, 2, 3, 4, 5, 6).toSet.getClass // class immutable.HashSet
...
输出
Suppose I have a Scala array
arr
ofInt
. Considerarr.toSet
. I know thattoSet
returns aSet
object. Is thisSet
aHashSet
, orTreeSet
in default?
都没有。这是一个 scala.collection.immutable.Set
.
这里是 the documentation for scala.Array.toSet
(which is actually scala.collection.IterableOnceOps.toSet
):
def toSet[B >: A]: Set[B]
可以看到,明确指定了return类型为Set
。