如何强制调用某些构造函数/函数来使用命名参数?

mfu*_*n26 20 named-parameters kotlin

我有一些构造函数和函数,我希望始终使用命名参数调用.有没有办法要求这个?

我希望能够为具有许多参数的构造函数和函数执行此操作,并且对于那些在使用命名参数时更清楚地读取的函数,等等.

mfu*_*n26 20

我通过使用Nothingstdlib 在Kotlin 1.0中找到了一种方法:

/* 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
Run Code Online (Sandbox Code Playgroud)

由于Array<Nothing>是在科特林非法的,对于一个数值vararg nothings: Nothing不能被创建在要传递(短反射的我想).这看起来有点像黑客,我怀疑在类型的空数组的字节码中有一些开销,Nothing但它似乎工作.

此方法不适用于无法使用的数据类主构造函数,vararg但这些可以标记为,private并且可以使用辅助构造函数vararg nothings: Nothing.

然而,这种方法在Kotlin 1.1中不起作用:"Forbidden vararg参数类型:无".:-(

值得庆幸的是,Kotlin 1.1并没有失去希望.您可以通过使用私有构造函数(如Nothing)定义自己的空类来复制此模式,并将其用作第一个varargs参数.当然,如果正式支持强制命名参数,则不必执行此操作.

  • 虽然这从未被语言设计所打算,但我赞赏你的聪明才智:) (19认同)