gpt4 book ai didi

kotlin - List > + List = List <任何>?

转载 作者:行者123 更新时间:2023-12-02 13:23:26 25 4
gpt4 key购买 nike

我有下面的代码有效。

class ListManipulate(val list: List<Char>, val blockCount: Int) {

val result: MutableList<List<Char>> = mutableListOf()

fun permute(sequence: List<Int> = emptyList(), start: Int = 0, count: Int = blockCount) {
if (count == 0) {
result.add(constructSequence(sequence))
return
}
for (i in start .. list.size - count) {
permute(sequence + i, i + 1, count - 1)
}
}

private fun constructSequence(sequence: List<Int>): List<Char> {
var result = emptyList<Char>()
for (i in sequence) {
result += list[i]
}
return result
}
}

但是,当我将 result从MutableList更改为普通列表时,即
    var result: List<List<Char>> = emptyList()
// ...
result += constructSequence(sequence)

我收到此错误 Type mismatch. Require: List<List<Char>>; Found: List<Any>
完整代码如下
class ListManipulate(val list: List<Char>, val blockCount: Int) {

var result: List<List<Char>> = emptyList()

fun permute(sequence: List<Int> = emptyList(), start: Int = 0, count: Int = blockCount) {
if (count == 0) {
result += constructSequence(sequence)
return
}
for (i in start .. list.size - count) {
permute(sequence + i, i + 1, count - 1)
}
}

private fun constructSequence(sequence: List<Int>): List<Char> {
var result = emptyList<Char>()
for (i in sequence) {
result += list[i]
}
return result
}
}

为什么 result + constructSequence(sequence)会导致 List<Any>而不是 List<List<Char>>

有没有办法我仍然可以使用普通的List>而不是可变列表?

最佳答案

CTRL +单击IDEA中的+,您将看到它带您进入以下功能:

/**
* Returns a list containing all elements of the original collection and then all elements of the given [elements] collection.
*/
public operator fun <T> Collection<T>.plus(elements: Iterable<T>): List<T> {
/* ... */
}

这意味着您将 elements的所有单个元素添加到接收器。也就是说,您将所有 T都添加到 List<List<T>>中。由于 List<T>不是 T,因此将得到 List<Any>

关于kotlin - List <List <Char >> + List <Char> = List <任何>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49570809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com