Kotlin默认参数:禁止零参数调用
在我的项目中,我有一个这样的功能:
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) }
这是不可能的,因为你使两个参数都是可选的。 你可以在方法体中添加一个检查,或者,我更喜欢提供适当的重载 :
fun doCoolStuff(arg1: Int) { doCoolStuff(arg1, null) } fun doCoolStuff(arg2: String?) { doCoolStuff(0, arg2) } fun doCoolStuff(arg1: Int, arg2: String?) {}
可能是我不明白,但这对我有用
fun doCoolStuff() { throw IllegalArgumentException("Can't do this") }
只需定义没有参数的方法并抛出异常。
您可以用零参数声明doCoolStuff()
,并将其标记为DeprecationLevel.ERROR
。
fun doCoolStuff(arg1: Int = 0, arg2: String? = null) {} @Deprecated("Should be called with at least one parameter", level = DeprecationLevel.ERROR) fun doCoolStuff() {}