root
root

Reputation: 491

How do I define a function def which accepts arguments and returns a value?

I would like to be able to define a function which accepts an argument (e.g. a File object), and returns something (e.g. a Boolean), and then pass that function (not the boolean!) to another function and have the accepting function call the sent function.

My background is in Java, and, although I know how to send a function which accepts no arguments and returns nothing in Scala, I can't seem to find a good explanation on the internet for how to do this.

I could implement the program in Java, but I would really like to know how to do it in Scala.

Upvotes: 3

Views: 647

Answers (1)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

First an example function (actually a method):

import java.io.File

def fileExists(file: File) = file.exists

and a way to pass that function (actually a method) as an argument to another function (actually... you know...):

def findFiles(files: Seq[File], predicate: (File) => Boolean) =
  files filter predicate

This method accepts a sequence of files and filters that sequence, picking only files passing a given predicate. In this case we return only existing files:

findFiles(Seq(new File("a.txt"), new File("b.txt")), fileExists)

See how elegantly we pass exists method as an argument? Or if you want to call the predicate manually:

def fileMatches(file: File, predicate: (File) => Boolean) =
  predicate(file)

Side note: "...actually a method"

The findFiles() method takes predicate function as an argument. However fileExists() is a method - this works due to a mechanism called eta-expansion - transparently wrapping methods into functions.

Upvotes: 3

Related Questions