w3resource

Anonymous Kotlin function: Concatenation of two strings


Write an anonymous Kotlin function to concatenate two strings and return the result.


Pre-Knowledge (Before You Start!)

Before attempting this exercise, you should be familiar with the following concepts:

  • Strings: A string is a sequence of characters, and Kotlin provides various methods to work with them, including concatenation.
  • Anonymous Functions: An anonymous function allows you to define a function without naming it. It can be stored in a variable and passed around like any other value.
  • String Concatenation: Concatenating strings in Kotlin can be done using the + operator. This joins two strings into one.
  • Function Types: The syntax for function types in Kotlin is (parameter types) -> return type. Understanding how to define and use function types is crucial for this exercise.

Hints (Try Before Looking at the Solution!)

Try to solve the problem with these hints:

  • Hint 1: Define an anonymous function that takes two string parameters and returns their concatenation.
  • Hint 2: Use the + operator inside the function to concatenate the two input strings.
  • Hint 3: Assign the anonymous function to a variable, and then call it with two string arguments.
  • Hint 4: After calling the function, print the concatenated result to verify the output.

Sample Solution:

Kotlin Code:

fun main() {
    val concatStrings: (String, String) -> String = fun(str1: String, str2: String): String {
        return str1 + str2
    }

    val string1 = "Kotlin "
    val string2 = "Exercises."

    val result = concatStrings(string1, string2)
    println("Concatenated string: $result")
}

Sample Output:

Concatenated string: Kotlin Exercises

Explanation:

In the above exercise -

  • We define an anonymous function called concatStrings with the type (String, String) -> String. It takes two strings as its parameters (str1 and str2) and returns the concatenation of the two strings.
  • Inside the concatStrings function, we simply use the + operator to concatenate str1 and str2.
  • In the main function, we define the concatStrings anonymous function and assign it to the variable concatStrings. We then call the concatStrings function passing two strings string1 and string2 as arguments, and store the result in the result variable.

Kotlin Editor:


Previous: Sum of odd numbers in a list.
Next: Average of squares in a list.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.