Scala: How to write the type of function that sortBy does?

I want to pass a parameter that List.sortBy jumps 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 get the same result as with this:

 myList.sortBy(_._1) 

What is the type of option in the sortAndMore function?

The Scala API for scala.collection.immutable.List says the following:

 def sortBy [B] (f: (A) β‡’ B)(implicit ord: Ordering[B]): List[A] 

I tried a few things, but I just don’t know the correct syntax, and I was out of luck. Any hints are much appreciated, especially with a pointer to why the syntax should be this way.

+4
source share
1 answer

Here is my solution (compiled 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)) 
+2
source

Source: https://habr.com/ru/post/1392015/


All Articles