I'm working exercises from the book Learning Scala and one question asks:
A popular use for implicit parameters is for a default setting that works most of the time but may be overridden in special cases. Assume you are writing a sorting function that takes lines of text, and the lines may start with a right-aligned number. If you want to sort using the numbers, which may be prefixed by spaces, how would you encode this ability in an implicit parameter? How would you allow users to override this behavior and ignore the numbers for sorting?
My solution:
def sortLines(l: List[String])(implicit o: Ordering[String]) = l.sorted
Unit test using Scala Test:
"Ch10" should "order lines starting with right-aligned numbers" in {
val l = List(" 2 a", " 1 b", " 3 c")
implicit val orderingByNumber: Ordering[String] = Ordering.by(_.trim.split("\\s")(0).toInt)
val orderingIgnoringNumber: Ordering[String] = Ordering.by(_.trim.split("\\s")(1))
Ch10.sortLines(l) should contain inOrder(" 1 b", " 2 a", " 3 c")
Ch10.sortLines(l)(orderingIgnoringNumber) should contain inOrder(" 2 a", " 1 b", " 3 c")
}
Problem is the test fails with a java.lang.NumberFormatException: For input string: "b"
. Why?