AlexeyGorovoy
AlexeyGorovoy

Reputation: 800

Kotlin default arguments: forbid zero arguments calls

In my project I have a function like this:

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

Which I want it to use it in following cases:

obj.doCoolStuff(101) // only first argument provided
obj.doCoolStuff("102") // only second argument provided
obj.doCoolStuff(103, "104") // both arguments provided

But not in this one:

obj.doCoolStuff() // illegal case, should not be able to call the function like this

How do I achieve this on the syntax level?

Upvotes: 2

Views: 340

Answers (4)

BakaWaii
BakaWaii

Reputation: 6992

You can declare doCoolStuff() with zero parameter and mark it as deprecated with DeprecationLevel.ERROR.

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

@Deprecated("Should be called with at least one parameter", level = DeprecationLevel.ERROR)
fun doCoolStuff() {}

Upvotes: 1

yole
yole

Reputation: 97338

There is no syntax in Kotlin that would allow you to accomplish what you need. Use overloaded functions (I'd use two, one for each required argument):

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

Upvotes: 5

Jan
Jan

Reputation: 74

Might be I don't understand but this works for me

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

Just define the method with no parameters and throw exception.

Upvotes: 0

s1m0nw1
s1m0nw1

Reputation: 82117

This is not possible because you made both arguments optional. You could add a check in the method body or, what I'd prefer, provide proper overloads:

fun doCoolStuff(arg1: Int) {
    doCoolStuff(arg1, null)
}

fun doCoolStuff(arg2: String?) {
    doCoolStuff(0, arg2)
}

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

Upvotes: 3

Related Questions