Different behavior when declaration type is different(Set vs TreeSet)

前端 未结 4 1102
囚心锁ツ
囚心锁ツ 2021-01-21 05:15
    var set = TreeSet(5,4,3,2,1)
    println(set)

    val diffSet: TreeSet[Int] = set
    // if I change above code to val diffSet: Set[Int] = set
    // the result is          


        
4条回答
  •  情书的邮戳
    2021-01-21 05:52

    Change the sig of genSet to return a SortedSet

    def genSet:SortedSet[Int] = {
      TreeSet(5, 4, 3, 2, 1)
    }
    

    This is probably some sort of bug. I would have expected your code to work too.

    I think map is the culprit. This results in the same behavior:

    for (i <- genSet.map(_ + 1)) { println(i) }
    

    And for(i <- genSet; x = i + 1) equates to for(x <- genSet.map({i => i + 1}))

提交回复
热议问题