我需要从列表中提取一个切片:
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 视为未解决的引用,因此我尝试添加扩展属性
private val Any?.size: Any
get()= this.length
但是我得到了长度尚未解析的参考。显然,我在函数中引入大小方面做错了。我该如何解决?
我对Kotlin非常了解,因此请避免发表表明我对该主题知识不足的评论。
答案 0 :(得分:1)
这是因为您正在使用泛型,并且 def get_prefix(bot, message):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
return prefixes[str(message.guild.id)]
bot = discord.Client()
bot = commands.Bot(command_prefix = get_prefix)
@bot.event
async def on_guild_join(guild):
with open('prefixes.json', 'r') as f:
prefixes = json.load(f)
prefixes[str(guild.id)] = '|'
with open('prefixes.json', 'w') as f:
json.dump(prefixes, f, indent=4)
可以是任何对象,没有<T>
或size
。也许您想将length
限制为具有大小/长度的某些东西的子类?
编辑:
或者,如果您要访问列表的大小,只需使用T
。
无论哪种方式,您可能只想检查一下,如果当前的foreach索引是否在限制范围内,则可以使用Ranges进行操作:
list.size