1

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?

2 Answers 2

5

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
}
Sign up to request clarification or add additional context in comments.

Comments

5

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.