1

I'm trying to translate the code from Java to Scala:

class Item {
  public long lng;
  public String str;

  Item(long lng, String str) {
   this.lng = lng;
   this.str = str;
  }
}

Item[] items = getItems(...) //doesn't really matter
int maxCount = getMaxCount()
for(int i = 0; i < maxCount && i < items.length; ++i) {
    System.out.println(String.format("%d %s",items[i].lng, items[i].str));
}

Here is my attempt:

class Item (val lng: Long, val str: String)
val items = Array(new Item(1, "11"), new Item(2, "22"))
val maxCount = getMaxCount
for {
      x <- items
      i <- 0 to maxCount
      if i < maxCount
  } println(x.lng.toString + " " + x.str)

Also, how can do that without for {...} using filterWith and foreach but without var?

It prints the string maxCount*2 times.

2 Answers 2

5

You need to declare your values as class members; as you have it defined, they are constructor parameters. Prefix them with val to make them also class members:

class Item(val lng: Long, val str: String)

Also, in the last line the error indicates s and l are not a members of x. Their names are str and lng.

You don't need i at all as far as I can tell.

val maxCount: Int = ...
items.take(maxCount).foreach { x => println(s"${x.lng} ${x.str}") }
2
  • well, yes, I just didn't pay attention, but it prints them maxCount*2 times.
    – user266003
    Oct 3, 2013 at 3:27
  • look at Java for loop and this is what I want.
    – user266003
    Oct 3, 2013 at 3:30
1

Using take as suggested by WeaponsGrade is a nice solution, but won't help you if you truly need something related to the index. A straight-forward conversion would go like this:

for (i <- 0 until (maxCount max items.length)) {

or, for more complex conditions than a simple max, you could write it like this:

for (i <- 0 until items.length if i < maxCount) {

This is not the same thing as the Java for loop -- the only way to accomplish exactly what Java does is using recursion or while loops.

Now, there are alternative ways of writing this. First, instead of 0 until items.length you could write items.indices, for any Scala collection.

Next, if you want both the item and its index at the same time, you could use this:

for ((x, i) <- items.zipWithIndex if i < maxCount) {

Using filterWith, you could write this:

items.indices.filterWith(i => i < maxCount).foreach { i => 
  println(s"${items(i).lng} ${items(i).str}")
}

Or pretty much any of the other alternatives. For instance, the zipWithIndex version becomes:

items.zipWithIndex.filterWith { 
  case (x, i) => i < maxCount 
}.foreach {
  case (x, i) => println(s"${x.lng} ${x.str}")
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.