paul paul - 26 days ago 12
Scala Question

Generic type with collection sorted operator

I´m trying to create an implicit class using generic, here the class

object Utils {

implicit class optionUtils(option: Option[Any]) {
def sortedList[T]:List[T] = {
val list:List[T] = option.get.asInstanceOf[List[T]]
list.sorted[T]
}
}
}


And here the invocation

jsonResponse.get("products").sortedList[String]


But seems like sorted is not compiling, and the compiler says.

Error:(8, 18) not enough arguments for method sorted: (implicit ord: scala.math.Ordering[T])List[T].
Unspecified value parameter ord.
list.sorted[T]
^


Any idea how to make it works?.

Regards.

Answer

You have to tell the compiler that T is restricted to an order-able type.

def sortedList[T: Ordering]:List[T] = { ...
Comments