w3resource

Anonymous Kotlin function: Check palindrome string


Write an anonymous Kotlin function to check if a string is a palindrome.


Pre-Knowledge (Before You Start!)

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

  • Anonymous Functions: An anonymous function is a function that is defined without a name, often used for short operations.
  • String Manipulation: Functions like toLowerCase() and replace() allow you to modify strings. toLowerCase() converts a string to lowercase, while replace() can remove unwanted characters using regular expressions.
  • Reversing Strings: The reversed() function reverses the order of characters in a string.
  • Regex: Regular expressions help in pattern matching and replacing specific characters in a string. In this case, we remove all non-alphanumeric characters.

Hints (Try Before Looking at the Solution!)

Here are some hints to help you solve the problem:

  • Hint 1: Create an anonymous function that takes a string as an argument and returns a Boolean.
  • Hint 2: To ignore case sensitivity, convert the string to lowercase.
  • Hint 3: Use a regular expression in replace() to remove any non-alphanumeric characters.
  • Hint 4: Compare the cleaned string with its reversed version using the reversed() function.
  • Hint 5: Return true if the string is a palindrome, otherwise return false.

Sample Solution:

Kotlin Code:

fun main() {
    val isPalindrome: (String) -> Boolean = { str ->
        val cleanStr = str.lowercase().replace(Regex("[^a-zA-Z0-9]"), "")
        cleanStr == cleanStr.reversed()
    }

    val str1 = "Madam"
    val str2 = "Kotlin"

    println("$str1 is a palindrome: ${isPalindrome(str1)}")
    println("$str2 is a palindrome: ${isPalindrome(str2)}")
}

Sample Output:

Madam is a palindrome: true
Kotlin is a palindrome: false

Explanation:

In the above exercise -

Inside "main()" function we define an anonymous function isPalindrome with the type (String) -> Boolean. This function takes a single string argument and returns a Boolean indicating whether the string is a palindrome or not.

The isPalindrome function implements the following steps:

  • It converts the input string to lowercase using toLowerCase() to ignore case sensitivity.
  • It removes any non-alphanumeric characters from the string using replace(Regex("[^a-zA-Z0-9]"), "").
  • It checks if the cleaned string is equal to its reversed version using the == operator.
  • The result of the equality comparison is returned as a Boolean value.

Go to:


PREV : Convert list of strings to uppercase with lambda.
NEXT : Calculate a factorial.

Kotlin Editor:


Improve this sample solution and post your code through Disqus

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.