user1002579
user1002579

Reputation: 129

Converting Java to Scala

I am trying to learn Scala, so can anyone tell me how to convert the following in scala:

for (int t = 0; true; t++)

Thank you in advance.

Upvotes: 1

Views: 388

Answers (4)

om-nom-nom
om-nom-nom

Reputation: 62835

With imperative style you can write (as you do in Java):

var t = 0
while(true) {
  t+=1
  ...
}

With lazy functional this could be:

def ints(n: Int = 0): Stream[Int] = Stream.cons(n, ints(n+1))
ints().map(t => ...)

Using built-in functions:

Iterator.from(0).map ( t => .... )

The common use case with such infinite structures, is to take infinite stream or iterator, perform some operations on it, and then take number of results:

Iterator.from(0).filter(t => t % 1 == 0).map(t => t*t).take(10).toList 

Upvotes: 19

Carlos Quintanilla
Carlos Quintanilla

Reputation: 13303

You can use while or for.

You can use for

for(i<-0 to 100) {
  println(i)
}

or you use until when you want to increment by N number

for(i <- 5 until 55 by 5) {
    println(i)
}

or you better use while

var i = 0
while(true) {
  ...
  i+=1
}

or also do-while

var i = 0
do {
    ...
    i += 1
} while(true)

Have a look at : http://www.simplyscala.com/ and test it out by yourself

Also, in my blog I did some posts about imperative scala where I used for and while loops you can have a look there.

http://carlosqt.blogspot.com/search/label/Scala

Upvotes: 4

tgr
tgr

Reputation: 3608

A simple for comprehension in scala looks mostly this way:

for (i <- 0 until 10) {
  // do some stuff
}

Upvotes: 2

Madoc
Madoc

Reputation: 5919

As I mentioned in the comments, your question does not seem to make much sense - please add more detail.

For now, the closest Scala translation I can come up with would be:

Stream from 0

Upvotes: 8

Related Questions