Reputation: 17617
How can I select the second smallest element after that a list has been sorted?
With this code I get an error and I do not understand why.
object find_the_median {
val L = List(2,4,1,2,5,6,7,2)
L(2)
L.sorted(2) // FIXME returns an error
}
Upvotes: 1
Views: 559
Reputation: 714
It's because sorted
receives implicitly an Ordering
argument, and when you do it like L.sorted(2)
the typechecker thinks you want to pass 2
as an Ordering
. So one way to do it in one line is:
L.sorted.apply(2)
or to avoid the apply
pass the ordering explicitly:
L.sorted(implicitly[Ordering[Int]])(2)
which I admit is somewhat confussing so I think the best one is in two lines:
val sorted = L.sorted
sorted(2)
(You may also want to adhere to the Scala convention of naming variables with lowercase).
Upvotes: 7