Signature of a function and function overloads in Kotlin

The Signature of a function in programming represents a kind of unique identifier of a function. By using the function signature, for example, a function in a group of functions with the same name can be uniquely identified and called.

The function signature in Kotlin always consists of the Name of the function as well as theirs Parameter list, including the Quantity, Types and Order of parameters, as well as the return type.

The following example illustrates these statements:

In this example, three functions have the same name sumOfNumbers, but differ in other components of the signature and are therefore clearly distinguished and recognized by the Kotlin compiler.

  • The signature of the first function is sumOfNumbers(Int, Int) -> Int, since they have two parameters of type Int has and one Int returns as a return value.
  • The signature of the second function is sumOfNumbers(Double, Double) -> Double, since they have two parameters of type Double has and one Double returns as a return value.
  • The signature of the third function is sumOfNumbers(Int, Double) -> Double, since it has a parameter of type Int and a parameter of type Double has and one Double returns as a return value.

There are several use cases in Kotlin where function signature is used. One of them is feature overloading.

Function overloading

By using different signatures, you can define functions with the same name but that perform different tasks within a code. This approach is called Function overloading (English: Function overloading) designated. It allows developers to create more flexible, consistent, and reusable code structures and helps improve code readability and understandability.

However, there is a special feature in Kotlin when it comes to using function signatures in function overloads. For function overloads, only the name of the function and its parameter list, including the number, types and order of the parameters, are taken into account. The return type is not taken into account in function overloading.

The example below shows how function overloading works:

In this example there were three functions with the same name sumOfNumbers declared that have different signatures. When calling the function sumOfNumbers The compiler automatically selects the required version for execution depending on the type, number and order of parameters. The return type is not taken into account. 

To understand this, we now declare two functions whose signatures differ only in the return type:

For the Kotlin compiler in the context of function overloading, both functions are used due to the consideration of the function name, the number and order of parameters considered identical. The return types Int and String are ignored. As a result, the compiler issues an error.  

Leave a Comment

Your e-mail address will not be published. Required fields are marked with * marked