Typyfying function signatures

Since you’re lifting the method (def) to function (passed as argument to sortMySeq) anyway you can do that once, i.e. change def bubbleSort(unsorted: Seq[Int]): Seq[Int] into val bubbleSort: Seq[Int] => Seq[Int] and then you can create ordinary type alias type SortAlgorithm = Seq[Int] => Seq[Int] and use it to type the val: val bubbleSort: SortAlgorithm.

BTW: What’s the problem with strategy pattern? With Scala 2.12+ it can be pretty concise:

trait SortAlgorithm {
  def apply(unsorted: Seq[Int]): Seq[Int]
}

val stdSort: SortAlgorithm =
  unsorted => unsorted.sorted

println(stdSort(Seq(3, 1, 2))) // prints: List(1, 2, 3)

Above solution has the advantage over standard functions (i.e. FunctionN traits) that you can name parameter (unsorted vs something generic in FunctionN traits) and have specific type SortAlgorithm instead of generic FunctionN which is easier to wrongly use (as Function1[Seq[Int], Seq[Int]] doesn’t have to be a sort algorithm).

1 Like