[英]What is the return type of toSet in Scala
假設我有一個Int
的 Scala 數組arr
。 考慮arr.toSet
。 我知道toSet
返回一個Set
object。 這是Set
a HashSet
還是默認的TreeSet
?
toSet
返回的值的編譯時類型是Set
def toSet[B >: A]: immutable.Set[B]
但是toSet返回的toSet
可能會有所不同,我們可以使用 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
...
哪個輸出
假設我有一個
Int
的 Scala 數組arr
。 考慮arr.toSet
。 我知道toSet
返回一個Set
object。 這是Set
aHashSet
還是默認的TreeSet
?
兩者都不。 它是一個scala.collection.immutable.Set
。
這是scala.Array.toSet
的文檔(實際上是scala.collection.IterableOnceOps.toSet
):
def toSet[B >: A]: Set[B]
如您所見,它明確指定返回類型為Set
。
https://github.com/scala/scala/blob/2.13.x/src/library/scala/collection/immutable/Set.scala
最多 4 個元素EmptySet
、 Set1
、 ...、 Set4
(如元組),然后是HashSet
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.