gpt4 book ai didi

generics - 提取切片-99个问题#18( Kotlin )

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

我需要从列表中提取一个 slice :

assertThat(slice(3, 7, "abcdefghijk".toList()), equalTo("defg".toList()))

我有:
@Suppress("unused")
fun <T> slice_(from: Int, to: Int, list: List<T>) = list.subList(from, to)

到目前为止,我的解决方案是:
fun <T> slice(from: Int, to: Int, list: List<T>): List<T> = list.filterIndexed { index, it ->
(index == from) && (it.size == to-from)
}

但是IDE认为size是 Unresolved reference ,因此我尝试添加扩展属性
private val Any?.size: Any
get()= this.length

但是我得到了长度尚 Unresolved reference 。显然,我在函数中引入大小方面做错了。我该如何解决?

Kotlin非常了解我,因此请避免发表表明我对该主题知识不足的评论。

最佳答案

这是因为您正在使用泛型,并且<T>可以是任何对象,而没有sizelength。也许您想将T限制为具有大小/长度的某些东西的子类?

编辑:
或者,如果您尝试访问列表的大小,则只需使用list.size即可。

无论哪种方式,您都可能只想检查一下,如果当前的foreach索引是否在限制范围内,则可以使用Ranges进行检查:

fun <T> slice(from: Int, to: Int, list: List<T>): List<T> = list.filterIndexed { index, it ->
index in from until to
}

关于generics - 提取切片-99个问题#18( Kotlin ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59325223/

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