为什么我每次尝试更改 Scala 中任何数据结构的值时都没有任何反应?

问题描述 投票:0回答:1

这通常发生在我使用会改变数组或列表的东西时。例如这里:nums.drop(i)。我尝试调试,但它甚至没有看到该行,如果您向我解释这种行为,我将不胜感激

    def findDuplicates(nums: Array[Int]): List[Int] = {
    nums.foldLeft(0)((accumValue, nextEl) => {
      if (nums.tail.contains(nextEl)) {
        accumValue
      } else {
        nums.drop(accumValue)
        accumValue
      }
    })

    nums.toList
  }
scala syntax
1个回答
0
投票

方法

drop
不会将元素放置到位。它返回一个新数组,其中没有删除的元素。而且你不以任何方式使用这个新数组(你不将这个值分配给一些
val
等),你只是忽略结果。

/** The rest of the array without its `n` first elements. */
def drop(n: Int): Array[A] = ...

https://github.com/scala/scala/blob/v2.13.10/src/library/scala/collection/ArrayOps.scala#L374

不是

def drop(n: Int): Unit
.

© www.soinside.com 2019 - 2024. All rights reserved.