Search code examples
stringscalaalphabetical

Scala method that returns the first string found in the alphabet/dictionary


For example this code

val stringTuple = ("BLACK", "GRAY", "WHITE")
firstInAlphabet(stringTuple)

Should return "BLACK". How would you define firstInAlphabet?

Personally I prefer simple and fast implementations over complicated ones that would cover a lot of cases.


Solution

  • t.productIterator.map(_.asInstanceOf[String]).min
    

    productIterator converts the elements of the tuple to an iterator. This looses the type information, so we have to cast the elements and then we use min to find the first.

    If you have non-String elements in your tuple this version should do the trick:

    t.productIterator.map(_.toString).min
    

    instead of casting to String it converts to a String.