Scala function: Check if a string is a palindrome
Write a Scala function to check if a given string is a palindrome.
Before you start!
To solve this problem, you should have a basic understanding of:
- What a palindrome is: A string that reads the same forward and backward.
 - Scala string manipulation techniques.
 - How to reverse a string in Scala.
 - How to compare two strings for equality.
 
Try before looking at the solution!
Think about how you can check if a string is a palindrome:
- How can you reverse a string in Scala?
 - Once reversed, how do you compare it with the original string?
 - How would you handle case sensitivity or spaces in the string?
 - Can you solve this problem using recursion or iteration instead of the built-in reverse method?
 
Sample Solution:
Scala Code:
object PalindromeChecker {
  def isPalindrome(str: String): Boolean = {
    val reversed = str.reverse
    str == reversed
  }
  def main(args: Array[String]): Unit = {
    val input1 = "madam"
    val isPalindrome1 = isPalindrome(input1)
    println(s"$input1 is a palindrome: $isPalindrome1")
    val input2 = "scala"
    val isPalindrome2 = isPalindrome(input2)
    println(s"$input2 is a palindrome: $isPalindrome2")
  }
}
Sample Output:
madam is a palindrome: true scala is a palindrome: false
Go to:
PREV : Reverse a Given String.
NEXT : Find the maximum element.
Scala Code Editor :
What is the difficulty level of this exercise?
