gpt4 book ai didi

generics - 将一些值连接到可变参数数组

转载 作者:行者123 更新时间:2023-12-01 11:17:46 25 4
gpt4 key购买 nike

我一直在尝试填补以下函数中的空白( val args = ... )。尝试了我能想到的一切,并找到了一个非常复杂的解决方案。我觉得有更好的方法,请建议一个更 Kotlin-y 的方式。我是否缺少概念/运算符/乐趣/类型?

class Result
interface Runner { fun execute(vararg tasks: String): Result }

fun Runner.debugExec(vararg tasks: String): Result {
// red: compile errors, mostly
//val args = tasks + "--debug"
//val args: Array<String> = tasks + "--debug"
//val args: Array<out String> = tasks + "--debug"
//val args = tasks + arrayOf("--debug")
//val args = tasks + arrayOf<String>("--debug")
//val args = tasks + listOf("--debug")
//val args = tasks + (arrayOf("--debug") as Array<out String>)
//val args = tasks + arrayOf<out String>("--debug") // Projections are not allowed here
//val args = tasks.toList() + "--debug" // spread operator doesn't work
//val args = tasks.plusElement("--debug") // cannot infer
//val args = "--debug" + tasks // it's .toString() and spread operator doesn't work
// yellow: works, but warns
//val args = (tasks as Array<String>) + "--debug" // unchecked cast
// green: but we must be able to do better, it's kotlin after all!
//val args = (tasks.toList() + "--debug").toTypedArray() // too many method calls
println(args)
return this.execute(*args)
}

我大部分时间得到的编译错误是这样的:
None of the following functions can be called with the arguments supplied.
Array<T>.plus(T)
  where T cannot be inferred for
   operator fun <T> Array<T>.plus(element: T): Array<T> defined in kotlin.collections
Array<out String>.plus(Array<out String>)
  where T = CapturedTypeConstructor(out String) for
  operator fun <T> Array<T>.plus(elements: Array<out T>): Array<T> defined in kotlin.collections
Array<out String>.plus(Collection<String>)
  where T = CapturedTypeConstructor(out String) for
  operator fun <T> Array<T>.plus(elements: Collection<T>): Array<T> defined in kotlin.collections

注: return this.execute(*tasks, "--debug")如果没有打印,和/或代码重复是可以接受的。

最佳答案

啊哈!找到了一个“更好”的解决方案,尽管它没有使用 + :

val args = arrayOf(*tasks, "--debug")

关于generics - 将一些值连接到可变参数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48454253/

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