我有一些构造函数和函数,总是希望使用命名参数来调用它们。有办法要求吗?
我希望能够对具有许多参数的构造函数和函数以及使用命名参数时更清晰地阅读的函数进行此操作。
在Kotlin 1.0中,您可以通过使用Nothing
stdlib 来执行此操作。
在Kotlin 1.1+中,您将获得“ Forbidden vararg parameter type:Nothing”,但您可以通过使用私有构造函数(如Nothing
)定义自己的空类并将其用作第一个varargs参数来复制此模式。
/* requires passing all arguments by name */
fun f0(vararg nothings: Nothing, arg0: Int, arg1: Int, arg2: Int) {}
f0(arg0 = 0, arg1 = 1, arg2 = 2) // compiles with named arguments
//f0(0, 1, 2) // doesn't compile without each required named argument
/* requires passing some arguments by name */
fun f1(arg0: Int, vararg nothings: Nothing, arg1: Int, arg2: Int) {}
f1(arg0 = 0, arg1 = 1, arg2 = 2) // compiles with named arguments
f1(0, arg1 = 1, arg2 = 2) // compiles without optional named argument
//f1(0, 1, arg2 = 2) // doesn't compile without each required named argument
就像Array<Nothing>
Kotlin中的违法行为一样,vararg nothings: Nothing
无法创建用于传递的值(我认为是缺乏反思的)。但是,这似乎有点hack,我怀疑用于空类型数组的字节码中会有一些开销,Nothing
但它似乎可以正常工作。
这种方法不适用于无法使用的数据类主构造函数,vararg
但可以将其标记为,private
而将辅助构造函数与一起使用vararg nothings: Nothing
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句