Scala HOF Syntax for a function that takes a generic argument T1 and returns a seq of generic result T2: Scala Play

Viewed 35

I am using Scala Play Framework and currently I have routes that handle requests with optional params limit and skip. Function definition is as shown below:

I have a route like this:

GET / controller.index(skip:Option[Int],limit:Option[Int])

And index does the following:

def index(skip:Option[Int],limit:Option[Int]): Action[AnyContent]

However I want to return a sequence of specific case classes like:

case class User(id: String,name: String)

Now I have a lot of routes like this where skip and limit are passed as optional query parameters, so Ideally I want to wrap all my other functions with a generic higher order function that looks like this:

case class Result[T] (
                     data: T,
                     skip: Option[Int],
                     limit: Option[Int]
                     )
object TestRunner extends App {
  def paginationHandler[T1,T2](f: T2 => Seq[T1], content: Result[T2]): Seq[T1] = {
    val result = f(content.data)
    val sliced = result slice(content.skip.getOrElse(0), content.skip.getOrElse(0) + content.limit.getOrElse(10))
    sliced
  }

  def getCategories(categories:Seq[String]): Seq[String] = categories

  val results = paginationHandler[String,Seq[String]](getCategories,Result[Seq[String]](Seq("Abc","Def","Ghi"),Some(0),Some(1)))
  println(results)
}

But I am struggling a lot with syntax. I need to understand how can I format the syntax of my index function so that it becomes a generic and returns Seq[T] where T is generic type instead of returning AnyContent.

0 Answers
Related