While trying to run the following snippet from Scala for the impatient:
val b = ArrayBuffer(1,7,2,9)
val bSorted = b.sorted(_ < _)
I get the following error:
error: missing parameter type for expanded function ((x$1, x$2) => x$1.$less(x$2))
val bSorted = b.sorted(_ < _)
Can somebody explain what might be going on here. Shouldn't the parameter type be inferred from the contents of the ArrayBuffer or do I need to specify it explicitly?
Thanks
.sorted
takes an implicit parameter of type Ordering
(similar to Java Comparator
). For integers, the compiler will provide the correct instance for you:
scala> b.sorted
res0: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 7, 9)
If you want to pass a comparison function, use sortWith
:
scala> b.sortWith( _ < _ )
res2: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2, 7, 9)
scala> b.sortWith( _ > _ )
res3: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(9, 7, 2, 1)
However, pay attention, although ArrayBuffer
is mutable, both sort methods will return a copy which is sorted, but the original won't be touched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With