0

Slowly moving into scala. Can either of these be done (apparently not the way I have them here)?

def genericFunc(param1:String, param2:String, specificFunc(param2:SpecficType):[T]):[T] =
{
    val interim:SpecificType = makeSpecificType(param1,param2)
    specificFunc(interim)
}


def genericFunc(param1:String, param2:String,specificFunc(param2:SpecficType):Object):Object ={
    val interim:SpecificType = makeSpecificType(param1,param2)
    specificFunc(interim)
}

or does the specificFunc need to be a trait/interface.

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
  • 1
    See also ["What's the difference between => , ()=>, and Unit=>"](http://stackoverflow.com/q/4543228/298389) for different kinds of functions you can pass-in – om-nom-nom Oct 02 '13 at 19:45

1 Answers1

3

To pass a function as an argument to another function you should have a following method signature:

def genericFunc[T](param1:String, param2:String, specificFunc: SpecficType => T): T = ???

SpecficType => T - is a function type which means that it needs a function which takes one argument of type SpecficType and returns a value of generic type T. Example:

def fromString[A](str: String, f: String => A) = f(str)

fromString("hello", str => str.toCharArray.sum.toInt)

you can optimize this futher:

fromString("hello", _.toCharArray.sum.toInt)

in this case fromString is a higher-order function. HOF are functions which can:

  • take another function as an argument
  • return a function

All this stuff is perfectly described in prof. Odersky book on - Programming in Scala

4lex1v
  • 21,367
  • 6
  • 52
  • 86