Reputation: 3244
def sort(s:String)={
val a= s.toCharArray ()
scala.util.Sorting.quickSort(array)
new String(a)
}
Upvotes: 0
Views: 150
Reputation: 12565
I don't see anything wrong with the sort method. If you want an in-place quicksort this is probably the best you are going to get.
Scala is not a pure functional language. It tries making a functional style pleasant to use, but if you want to use imperative style for performance or other reasons there is nothing wrong with it. In fact in addition to allowing functional style, scala is also a much better OO language than java.
See the talk from Martin Odersky, the creator of the language, about when to use mutable state. ScalaDays 2013 Keynote
In any case, as long as mutable state is confined to the local variables of a method, it is pretty harmless and easy to reason about. The sort method is pure / referentially transparent from the outside even though it uses mutable state inside.
By the way: if you want an immutable transform version of sort that works on strings, it also exists. It probably does something similar to your sort method internally.
scala> "BCAD".sorted
res5: String = ABCD
Upvotes: 4