简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM