tysheng
tysheng

Reputation: 47

kotlin overload method with default parameter

Here is the scenario, I got the below two methods.

fun foo(p1:Int,p2:String?=null)

fun foo(p1:Int,p2:Int=0)

How do I refer to the specific method with foo(1)?

Upvotes: 3

Views: 2346

Answers (1)

Jayson Minard
Jayson Minard

Reputation: 85996

This is an error if the caller only has one parameter:

foo(1) // error

Error:(Y, X) Kotlin: Overload resolution ambiguity:

public fun foo(p1: Int, p2: Int = ...): Unit defined in mypackage in file MyFile.kt

public fun foo(p1: Int, p2: String? = ...): Unit defined in mypackage in file MyFile.kt

So you have to name them differently or provide another differentiator (another parameter) so that the compiler knows which option to choose. It has no way to imagine what the second parameter might be to chose a default value either.

You could also combine it into one function having both of the optional parameters present if you can make your logic work from that (maybe not).

Or have them just named with two related names that also describes the difference, for example for some ficticious method:

calcValueFromInt(p1: Int, p2: Int = 0) { ... }
calcValueFromString(p1: Int, p2: String? = null) { ... } 

This improves readability anyway.

Upvotes: 3

Related Questions