Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing parameter type for expanded function in Scala ArrayBuffer

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

like image 782
sc_ray Avatar asked Apr 12 '12 14:04

sc_ray


1 Answers

.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.

like image 96
paradigmatic Avatar answered Oct 14 '22 07:10

paradigmatic