'scala string Tail recursion with pattern match

I am trying to write a tail recursion function to reverse string, here is the code, some reason I am not sure if the pattern match condition is preventing it from getting the reversed string as output

def revstring(str:String):String={
  @tailrec
  def rev(str:String,r:String):String={ 
    str match{
      case s if s.head==null =>null
      case x if x.tail.isEmpty => ""
      case _=> rev(str.tail, str.head +r) 
    }
  }
  rev(str,"")}println(revstring("Mississipi"))
}


Solution 1:[1]

s.head is never null. It'll throw an exception if the string is empty (or if it is null, which it should never be - nulls should never really appear in scala code). Also, you are returning too early - x.tail.isEmpty means you still have one char remaining to process. Finally, you always return "" instead of the actual result.

Something like this should work:

  str match {
     case "" => r
     case s => rev(s.tail, s.head + r)
  }

As mentioned in the comment, manipulating strings like this isn't very performant. So, in real life you'd probably want to convert it into a list, reverse the list, and then .mkstring to put it back together.

Solution 2:[2]

I Have created function which reverse the string using scala's tail recursion

def reverseString(str:String) = {
@tailrec
def reverseStringHelper(strTail:List[Char],reversedString :List[Char]):List[Char] = {
  strTail match {
    case Nil => reversedString
    case head :: tail => {
      reverseStringHelper(tail,head :: reversedString)
    }
  }
}
reverseStringHelper(str.toList,List[Char]()).mkString
}

If you found the answer helpful, please accept it.

Github Gist: https://gist.github.com/Deepak-nebhwani/0f0981027b61ff9f50904662614e7b7f

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Deepak Nebhwani