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

我有一些构造函数和函数,我总是要使用命名参数来调用。 有没有办法要求这个?

我希望能够为具有多个参数的构造函数和函数以及那些在使用命名参数时更清晰地阅读的函数做到这一点。

我已经找到了一种方法来在Kotlin 1.0中使用stdlib中的Nothing

 /* 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参数的值就是vararg nothings: Nothing不能被创建(通过反思我猜不到)。 这似乎是一个黑客,但我怀疑有一些类型的空数组的字节码的开销,但它似乎工作。

这种方法不适用于不能使用vararg数据类主构造函数,但是这些构造函数可以标记为private而次级构造函数可以使用vararg nothings: Nothing标记vararg nothings: Nothing

但是,这种方法在Kotlin 1.1中不起作用:“禁止可变参数类型:无”。 🙁

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