• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Scala functions

 
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 59
6
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 San
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 San
Ranch Hand
Posts: 10198
3
Mac PPC Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 59
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
reply
    Bookmark Topic Watch Topic
  • New Topic