paul
paul

Reputation: 13471

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.

Upvotes: 0

Views: 71

Answers (1)

jwvh
jwvh

Reputation: 51271

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

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

Upvotes: 4

Related Questions