Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin default arguments: forbid zero arguments calls

Tags:

syntax

kotlin

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?

like image 283
AlexeyGorovoy Avatar asked Mar 07 '26 04:03

AlexeyGorovoy


1 Answers

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) }
like image 68
yole Avatar answered Mar 10 '26 07:03

yole



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!