Photo by Allie Smith on Unsplash

In the first article of this series, we reviewed the declaration of variables and constants in both Swift and Kotlin. We continue these posts by comparing function features as well.

In Kotlin

We use the reserved keyword “fun” to declare a function. Function parameters are enclosed in parentheses and the return type is preceded by a : symbol.

fun areValidCredentials(user : String, pass : String) : Boolean {
   //XXX: statements here...
   return true
}

The former function has a function with a block body, because it has several statements enclosed with brackets. But functions in Kotlin can also have an expression body instead, when containing a single statement, which is specified after the = symbol.

fun addNumbers(num1 : Int, num2 : Int) = num1 + num2

As you can see, with expression bodies brackets are omitted and return type is inferred from the expression itself. Keyword “return” is supressed too.

When calling a function, we can specify the parameter names followed by the = symbol and the corresponding value, so we specify the meaning for each value:

val result = addNumbers(num1 = 10, num2 = 23)

In Swift

As usual when comparing these languages, the declaration is very similar. But in this case, we use the “func” keyword (ending with a c) for function declaration. Moreover, the return type is preceded by the -> symbol instead.

func areValidCredentials(user : String, pass : String) -> Bool {
   //statements here...
   return true
}

In order to improve readability, function parameters in Swift have 2 identifiers:

  • argument labels: public identifiers, used when invoking the function
  • param names: private identifiers, used in the function implementation

Arg labels are defined for each element in the parameter list, before the param name itself:

// Provide a lang code for a given language. Ie: "english" -> "en"
// for is the arg label
// language is the param name
func getLanguageCode(for language: String) -> String {
   var code = ""

   //more statements here... 

   return code
}

When calling the previous function with arg labels, we use the : symbol after the arg label, but before the current value. Many IDE’s like Visual Studio fill in automatically the labels:

let code = getLanguageCode(for: "spanish")

Param names are mandatory, but argument labels can be skipped by using the _ character in their place.

// Provide a lang code for a given language. Ie: "english" -> "en"
// no arg label
// language is the param name
func getLanguageCode(_ language: String) -> String {
   var code = ""

   //...

   return code
}

In this case, the call to the function would be:

let code = getLanguageCode("spanish")

Similar to expression bodies, in Swift the return statement of any function can be omitted when the function contains only one statement:

func welcome(for user: String) -> String {
   //value is returned even if no explicit return keyword
   "Welcome back, \(user)!"
}

Common properties

Kotlin and Swift assign types to functions. A function type is derived from the parameter types and its return type. This feature allow us to treat functions as high level blocks, which can be passed as parameters or returned by other functions.

In order to improve readability, both programming languages optionally use parameter names when invoking a method.

Default parameter values are used when some params are not specified in a function call. If we have the following function declaration:

fun multiply(number : Int, times : Int = 1) = number * times

… then we can ommit the last parameter value, so the default value will be applied in the times param:

//XXX: both calls are correct
val result = multiply(number= 10)
val anotherResult = multiply(number= 10, times= 2)

Default parameter values may come in handy in order to avoid function overloading, present in other languages like Java.

On the other hand, considering its scope, both Kotlin and Swift support several types of functions:

  • global or top-level functions, declared outside any class
  • method functions, declared inside a class
  • local functions, declared inside another function
class Person(...) {

    /**
     * METHOD function
     */
    fun validateProperties() : Boolean {
        
        /**
         * LOCAL, inner function (declared inside another one)
         */ 
        fun validateField(value : String) = !value.isEmpty() 
        
        //XXX: local function can be called only from surrounding scope
        return validateField(this.name) && validateField(this.surname)
    }
}

Besides from that, both languages support extensions functions, used to complement the behaviour of some existing class, even if we can’t access it directly.

Wrapping up…

Function features are very much alike in Kotlin and Swift. Main differences between both languages reside in syntax elements (like keywords used when declaring blocks of code or symbols used as separators) rather than semantic features.

If you want to play some more with functions, you can find a sample code in the following link:

https://pl.kotl.in/YyLMLB_kX

References

https://docs.swift.org/swift-book/LanguageGuide/Functions.html

https://kotlinlang.org/docs/reference/functions.html

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: