A scala implementation of the Java trim method I'm a Scala beginner and looking at the trim() method of the Java API.  I noticed side effects, so I attempted to implement a functional version in Scala.

Here is the Java version: 

public String trim() {
int len = count;
int st = 0;
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */

while ((st &lt; len) &amp;&amp; (val[off + st] &lt;= ' ')) {
    st++;
}
while ((st &lt; len) &amp;&amp; (val[off + len - 1] &lt;= ' ')) {
    len--;
}
return ((st &gt; 0) || (len &lt; count)) ? substring(st, len) : this;
}


My Scala version iterates over a string, and when it encounters a space char, the tail of the string is returned. The entire string is then reversed, so it can access the trailing whitespace. This new string is iterated over until a space char is encountered and the tail of this string is returned. This new string is then reversed again to maintain the original string order: 

def trim(stringToTrim : String) : String = {
    def removePreString[String](list : List[String]) : java.lang.String = list match {

        case head :: tail =&gt; {
            if(head.toString.equals(" ")){
                removePreString(tail)
            }
            else {
                head.toString + tail.mkString
            }
        }
    }//end removePreString

    val preString =    removePreString(stringToTrim.toList)
    val reveresedString = preString.toList.reverse
    val reveresedPostString = removePreString(reveresedString)
  reveresedPostString.reverse

}//end trim 


How can this code be improved?  Does it seem wasteful reversing the string twice?
No good idea about the concern of reversing the list twice. But you may


Let you inner function return a List instead of a string thus having less conversions from list to string and string to list.
Change your match to the following pattern (not tested):

case " " :: tail =&gt; removePreString(tail)
case _ =&gt; _



I just realize you could also use on a list def dropWhile(p: (A) ⇒ Boolean): List[A] which drops longest prefix of elements that satisfy a predicate. You could then chain dropWhile not a space | reverse | dropwhile not a space | reverse...