Anonymous Kotlin function: Concatenation of two strings
Kotlin Lambda: Exercise-13 with Solution
Write an anonymous Kotlin function to concatenate two strings and return the result.
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/kotlin-exercises/lambda/kotlin-lambda-exercise-13.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics