Todd M
Todd M

Reputation: 1010

Scala - methods with functions as arguments

Trying to get my head around using functions as arguments to methods. For a simple example let's use:

case class IntegrationOption(id: Option[Long], name: String, iconUrl: String)

val availableOptions = List(
   IntegrationOption(Some(1), "blah1", "dsaadsf.png"),
   IntegrationOption(Some(2), "blah2", "dsaadsf.png")
)

I want to pass in a function to something like this:

def getIntegrationOption(ARG) = {
  availableOptions.find(ARG)
}

where ARG might be:

x => x.id == Option(id)

or

x => x.name == "blah1"

Ideas? Thoughts?

Upvotes: 1

Views: 558

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340693

This should work:

def getIntegrationOption(predicate: IntegrationOption => Boolean) = 
  availableOptions.find(predicate)

Now you can use it as follows:

getIntegrationOption(_.iconUrl == "dsaadsf.png")

Note that since IntegrationOption is already a case class, you can do some fancier searching with pattern matching and partially applied functions:

availableOptions.collectFirst{
  case IntegrationOption(Some(1), name, _) => name
}

or:

availableOptions.collectFirst{
  case io@IntegrationOption(_, "blah2", _) => io
}

Upvotes: 5

Dan Simon
Dan Simon

Reputation: 13117

All you have to do is declare a parameter that's a function, then you can use the parameter like any other function or pass it to higher-order functions like find:

def getIntegrationOption(f: IntegrationOption => Boolean) = {
  availableOptions.find(f)
}
getIntegrationOptions(x => x.name == "blah1")
//or you could do just
getIntegrationOptions(_.name == "blah1")

Upvotes: 5

Related Questions