英文:
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 -> line.split(delimiter).forEach { word -> word.dropWhile { char -> char == ' ' } } }
However i get a Type Mismatch:
Error:(17, 16) Kotlin: Type mismatch: inferred type is List<Unit> but List<List<String>> 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<Unit>
:
this.split(lineDelimiter).map { line -> line.split(delimiter).forEach { word -> word.dropWhile { char -> char == ' ' } } }
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 ->
line.split(delimiter)
.map { word ->
word.dropWhile { char -> char == ' ' }
}
}
Main change: forEach
is statement-like operator, it returns Unit (and should do mutation). map
is expression-like operator, it converts List<X>
to List<Y>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论