Kotlin – 使用forEach处理嵌套列表时出现类型不匹配错误

huangapple go评论64阅读模式
英文:

Kotlin - Nested lists with forEach with TypeMismatch

问题

我正在编写一个函数,将纯文本CSV文件转换为二维数组,但我想在分隔符后面加上空格。我想要的返回类型是List<List>。我的逻辑是:

val mapped = this.split(lineDelimiter).map { line ->
    line.split(delimiter).map { word -> word.trim() }
}

然而,我得到了类型不匹配的错误:

错误:(17, 16) Kotlin: 类型不匹配推断类型为List<Unit>但期望的是List<List<String>>

我已经重写了这个函数,使其在不使用forEach函数的情况下变得更加函数式,但看起来相当丑陋。

英文:

I am writing a function that converts a plain-text CSV file to a two-dimensional Array but i want to be able to put a space after my delimiter. The return type i want is List<List<String>>. My logic is:

    val mapped = this.split(lineDelimiter).map { line -&gt; line.split(delimiter).forEach { word -&gt; word.dropWhile { char -&gt; char == &#39; &#39; } } }

However i get a Type Mismatch:

Error:(17, 16) Kotlin: Type mismatch: inferred type is List&lt;Unit&gt; but List&lt;List&lt;String&gt;&gt; was expected

I have already rewritten this to be functional without using the forEach function, but thats quite ugly.

答案1

得分: 0

以下是翻译好的部分:

下面表达式的结果是 List<Unit>

this.split(lineDelimiter).map { line ->
    line.split(delimiter).forEach { word ->
        word.dropWhile { char -> char == ' ' }
    }
}

看起来你想将文本分成多行,然后将每行分成多个部分,然后更新每个单词。所以代码应该像这样:

this.split(lineDelimiter).map { line ->
    line.split(delimiter)
        .map { word ->
            word.dropWhile { char -> char == ' ' }
        }
}

主要变化:forEach 是类似语句的操作符,它返回 Unit(应该执行变更)。而 map 是类似表达式的操作符,它将 List<X> 转换为 List<Y>

英文:

The result of expression below is List&lt;Unit&gt;:

this.split(lineDelimiter).map { line -&gt; line.split(delimiter).forEach { word -&gt; word.dropWhile { char -&gt; char == &#39; &#39; } } }

Looks like you want to split text to lines and then split each line to parts and next update each word. So code will be like this:

this.split(lineDelimiter).map { line -&gt;
    line.split(delimiter)
        .map { word -&gt;
            word.dropWhile { char -&gt; char == &#39; &#39; }
        }
}

Main change: forEach is statement-like operator, it returns Unit (and should do mutation). map is expression-like operator, it converts List&lt;X&gt; to List&lt;Y&gt;

huangapple
  • 本文由 发表于 2020年1月3日 18:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定