scalashapelessarity

Function taking another function of arbitrary arity as argument


I have a series of functions that accept a function as an argument (func), and the only difference in them is that func accepts different numbers of parameters.

  def tryGet[T,A](func: (A) => T)
  def tryGet[T,A,B](func: (A,B) => T)
  ...       [T,A,B,C...]

Is there a way to make a function accept a function with any length argument list?

I tried using variable length argument lists, eg func:(A*) but had trouble passing any functions in as it now requires a Seq[A].


Solution

  • You can try to use shapeless.ops.function.FnToProduct

    def tryGet[F: FnToProduct](func: F) = ???
    
    val f1: Int => String = ???
    val f2: (Int, Int) => String = ???
    val f3: (Int, Int, Int) => String = ???
    
    tryGet(f1)
    tryGet(f2)
    tryGet(f3)
    

    https://github.com/milessabin/shapeless/wiki/Feature-overview:-shapeless-2.0.0#facilities-for-abstracting-over-arity