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

fun doCoolStuff(arg1: Int = 0, arg2: String? = null) {
}

我希望它在以下情况下使用它:
obj.doCoolStuff(101) // only first argument provided
obj.doCoolStuff("102") // only second argument provided
obj.doCoolStuff(103, "104") // both arguments provided

但不是在这个:
obj.doCoolStuff() // illegal case, should not be able to call the function like this

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

最佳答案

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

fun doCoolStuff(arg1: Int, arg2: String? = null) { ... }
fun doCoolStuff(arg2: String?) { doCoolStuff(defaultIntValue(), arg2) }

09-10 16:31