Kotlin 默认参数:禁止零参数调用

Ale*_*voy 2 syntax kotlin

在我的项目中,我有这样的功能:

fun doCoolStuff(arg1: Int = 0, arg2: String? = null) {
}
Run Code Online (Sandbox Code Playgroud)

我希望它在以下情况下使用它:

obj.doCoolStuff(101) // only first argument provided
obj.doCoolStuff("102") // only second argument provided
obj.doCoolStuff(103, "104") // both arguments provided
Run Code Online (Sandbox Code Playgroud)

但不是在这个:

obj.doCoolStuff() // illegal case, should not be able to call the function like this
Run Code Online (Sandbox Code Playgroud)

如何在语法级别上实现这一目标?

yol*_*ole 5

Kotlin 中没有任何语法可以让您完成所需的任务。使用重载函数(我会使用两个,每个必需参数一个):

fun doCoolStuff(arg1: Int, arg2: String? = null) { ... }
fun doCoolStuff(arg2: String?) { doCoolStuff(defaultIntValue(), arg2) }
Run Code Online (Sandbox Code Playgroud)