ln2v
ln2v

Reputation: 109

Scala: How do I write the type of the function that sortBy takes?

I want to pass the parameter that List.sortBy takes through to another function. My code looks something like this:

//Scala
def sortAndMore(list: List[(String, _)], sortFn: Option[???] = None) = {
  val maybeSortedList = sortFn match {
    case None => list
    case Some(fn) => list.sortBy(fn)
  }
  // do some more stuff with this list
}

val myList = ("one", 1)::("three", 3)::("two", 2)::Nil
sortAndMore(myList, Some(_._1 /*???*/)) 

So in the end I want to have the same result as this gives:

myList.sortBy(_._1)

What is the type of Option in the sortAndMore function?

The Scala API for scala.collection.immutable.List says this:

def sortBy [B] (f: (A) ⇒ B)(implicit ord: Ordering[B]): List[A] 

I tried several things, but I just don't know the correct syntax, and wasn't lucky guessing it. Any hints are very much appreciated, especially with a pointer to why the syntax has to be that way.

Upvotes: 4

Views: 355

Answers (1)

Christopher Chiche
Christopher Chiche

Reputation: 15335

Here is my solution (compiles on my terminal)

def sortAndMore(list: List[(String,_)], sortFn: Option[((String,_))=>String] = None) = {
  val maybeSortedList = sortFn match {
    case Some(fn) => list.sortBy(fn)
    case None => list
  }
}

sortAndMore(myList, Some(_._1))

Upvotes: 2

Related Questions