File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Scala and the fly likes how this code is working? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Languages » Scala
Bookmark "how this code is working?" Watch "how this code is working?" New topic

how this code is working?

Pankaj Mittal
Ranch Hand

Joined: Jul 09, 2008
Posts: 32
Hii guys !!

I'm very new to Scala and going through some tutorials and one of them I found this code

I know it is returning list of prime integers but I couldn't know how this folder is working...can somebody help me??

Thanks in advance !!

2008 SCJP(5.0) 88%
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14915

The operator /: is the fold left operator. It is applied here on an empty list of Int and lst.

The thing on the right side is a function literal, that takes two parameters x and y and returns what the if-statement evaluates into, which is x if y is even, and x + y if y is odd.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
The code you're looking at isn't returning a list of prime integers.

Building on what Jesper wrote, Ill try to translate the code into Java for you:

As an aside, stylistically, I really dislike /: and :\, I much prefer the foldLeft and foldRight.

However, you must remember that foldRight is not tail-recursive and can blow the stack for large lists.

Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

I see odd integers returned, not primes, and would prefer a filter instead:
Pankaj Mittal
Ranch Hand

Joined: Jul 09, 2008
Posts: 32
Thanks guys !!!
I agree. Here's the link:
subject: how this code is working?
It's not a secret anymore!