" is used in Scala I read a lot of code snippets in scala that use the => symbol, but I could never understand...">

Can anyone explain how the symbol "=>" is used in Scala

I read a lot of code snippets in scala that use the => symbol, but I could never understand it. I tried to search the Internet, but could not find anything comprehensive. Any pointers / explanation of how / can be used will be really helpful.

(More specifically, I also want to know how the operator enters the picture in functional literals)

+7
source share
1 answer

More than passing values ​​/ names, => used to define a function literal, which is an alternative syntax used to define a function.

Sample time. Say you have a function that accepts another function. The collections are full of them, but we will choose filter . filter , when used in a collection (e.g. List), will output any element that forces the function you provide to return false.

 val people = List("Bill Nye", "Mister Rogers", "Mohandas Karamchand Gandhi", "Jesus", "Superman", "The newspaper guy") // Let only grab people who have short names (less than 10 characters) val shortNamedPeople = people.filter(<a function>) 

We could pass the real function from another place ( def isShortName(name: String): Boolean , maybe), but it would be better to just put it right there. Alas, we can, with functional literals.

 val shortNamedPeople = people.filter( name => name.length < 10 ) 

We have created a function here that takes a String (since people is of type List[String] ) and returns a boolean. Pretty cool, right?

This syntax is used in many contexts. Say you want to write a function that takes another function. This other function should take in String and return Int.

 def myFunction(f: String => Int): Int = { val myString = "Hello!" f(myString) } // And let use it. First way: def anotherFunction(a: String): Int = { a.length } myFunction(anotherFunction) // Second way: myFunction((a: String) => a.length) 

Here is what literals are. Returning to by-name and by-value , there is a trick in which you can force the parameter to not be evaluated until you want it. Classic example:

 def logger(message: String) = { if(loggingActivated) println(message) } 

This looks good, but message actually evaluated when the logger called. What if message takes time to evaluate? For example, logger(veryLongProcess()) , where veryLongProcess() returns a string. Oops? Not really. We can use our knowledge of function literals to make veryLongProcess() not be called until it is needed.

 def logger(message: => String) = { if(loggingActivated) println(message) } logger(veryLongProcess()) // Fixed! 

logger now accepts a function that takes no parameters (hence bare => on the left). You can still use it as before, but now message is only evaluated when it is used (in println ).

+14
source

All Articles