Reputation: 585
I am trying to make sense of a custom Iterator in Scala written by another programmer. I am having trouble understanding the function declarations. They look like anonymous functions to me, but I simply can't wrap my head around them fully.
I did some reading about Anonymous Functions in Scala , and I found this resource [http://www.scala-lang.org/old/node/133] helpful, but I still cannot read the above functions and make sense of them completely.
Here is the code:
class MyCustomIterator(somePath: Path, someInt: Int, aMaxNumber: Int) {
def customFilter:(Path) => Boolean = (p) => true
// Path is from java.nio.files.Path
def doSomethingWithPath:(Path) => Path = (p) => p
}
I would like to understand these understand these functions. What is the return type really? What is the body of the function?
.
Upvotes: 2
Views: 411
Reputation: 67135
(For the first def
) The parts after the colon and before the equals sign are the return type. So, the return type is:
Path => Boolean
Which denotes a function signature.
Now, breaking that down, the item on the left of the arrow is the parameters of a function. The right hand side is the return type of the function.
So, it is returning a function that accepts a Path
and returns a Boolean
. In this case, it is returning a function that will accept a Path
and return true
no matter what.
The second def
returns a function that accepts a Path
and returns another Path
(the same Path
in this case)
An example usage would be to use them as follows:
iter.customFilter(myPath) //returns true
or
val pathFunction = iter.customFilter;
pathFunction(myPath) //returns true
iter.doSomethingWithPath(myPath) //returns myPath
or
val pathFunction = iter.doSomethingWithPath
pathFunction(myPath) //returns myPath
Upvotes: 5