File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Scala and the fly likes Scala functions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Languages » Scala
Bookmark "Scala functions" Watch "Scala functions" New topic
Author

Scala functions

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

How could I use the following function?

def func = { x: Int => Int }

When I call func, I get a reference to a function that takes an Int and returns an Int. How do I make use of that function reference, pass a function that simply multiplies the input parameter?


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Sresh Rangi
Ranch Hand

Joined: Nov 28, 2012
Posts: 39
    
    1
func doesn't return an Int; it literally returns Int. It ignores the parameter and returns the same thing every time:



A function that returns an Int can be written as:



and a function that takes such a function as a parameter can be written as:

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

Thanks for that!

I'm trying to get my head around another one!



contents is a parameter-less function. How does contents(0) does not throw an error?
Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

Is it like this in Java?



Is it a feature of the parameter-less methods in Scala that I can use the return values inside the parenthesis?
Sresh Rangi
Ranch Hand

Joined: Nov 28, 2012
Posts: 39
    
    1
Yes, it's the same as "contents()[0]" in Java. The method can't be called with any parameters so the parenthesis aren't used for arguments. Contents is called first, and then the parenthesis access the returned array by index:



This is different from a method with an empty parameter list which can be called with or without parenthesis:

 
Consider Paul's rocket mass heater.
 
subject: Scala functions
 
Similar Threads
Static/Non-Static
Question about Javascript object members.
Passed By Reference?
Labels
Loading a file and executing it