Ben Chuanlong Du's Blog

It is never too late to learn.

Named Arguments in Kotlin

Function Overload and Named Arguments

  1. Function overload might cause tricky invoking bugs if you change the signature of an overloaded function. You should always be careful when you change the signature of an overloaded function. There is a graceful way of resolving this kind of issues in Kotlin (and similarly in Scala and Python), which is to use named arguments. If you invoke an function with named arguments, it is relatively robust to change of order of arguments and it fails fast if you change the names of arguments.
In [1]:
import kotlin.math.pow

fun myPower(base: Double, exponent: Double): Double {
    return base.pow(exponent)
}
Out[1]:
null
In [2]:
myPower(2.0, 3.0)
Out[2]:
8.0
In [3]:
myPower(base=2.0, exponent=3.0)
Out[3]:
8.0
In [4]:
myPower(exponent=3.0, base=2.0)
Out[4]:
8.0

Default Values of Parameters

In [7]:
import kotlin.math.pow

fun myPower2(base: Double, exponent: Double = 2.0): Double {
    return base.pow(exponent)
}
Out[7]:
null
In [9]:
myPower2(3.0)
Out[9]:
9.0
In [ ]:

Comments