简体   繁体   中英

Scala: understanding anonymous function syntax

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?

.

(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:

First method:

iter.customFilter(myPath) //returns true

or

val pathFunction = iter.customFilter;
pathFunction(myPath) //returns true

Second method:

iter.doSomethingWithPath(myPath) //returns myPath

or

val pathFunction = iter.doSomethingWithPath
pathFunction(myPath) //returns myPath

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM