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

时间:2017-09-08 11:53:06

标签: syntax 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

如何在语法级别实现此目的?

4 个答案:

答案 0 :(得分:4)

Kotlin中没有语法允许您完成所需的操作。使用重载函数(我使用两个,每个必需参数一个):

[1, 2, 3, 4, 5]

答案 1 :(得分:3)

这是不可能的,因为你使两个参数都是可选的。你可以在方法体中添加一个检查,或者我更喜欢提供正确的重载

.InlineShapes.AddPicture(".\relPath\to\myImage.jpg")

答案 2 :(得分:0)

您可以使用零参数声明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() {}

答案 3 :(得分:0)

我可能不明白但这对我有用

fun doCoolStuff() {
    throw IllegalArgumentException("Can't do this")
}

只需定义没有参数的方法并抛出异常。

相关问题