如何强制调用某些 constructors/functions 以使用命名参数?

How can I force calls to some constructors/functions to use named arguments?

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

我希望能够为具有许多参数的构造函数和函数以及使用命名参数时阅读起来更清楚的构造函数和函数等执行此操作

在 Kotlin 1.0 中,您可以使用标准库中的 Nothing 来完成此操作。

在 Kotlin 1.1+ 中,您将获得“禁止的可变参数类型:无”,但您可以通过使用私有构造函数(如 Nothing)定义自己的空 class 来复制此模式,并且将其用作第一个可变参数。

/* 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 的数据 class 主构造函数,但这些构造函数可以标记为 private 并且辅助构造函数可以与 vararg nothings: Nothing 一起使用.