0

I have some java code I am trying to convert to scala:

package hello;

class HelloWorldApp {
    public static void main(String[] args) {
            public SortedMap<Long, Long> toDates = new TreeMap<>();

            Iterator<Long> iterLong = toDates.keySet().iterator();
            while( iterLong.hasNext() )
            {
                System.out.println("TEST");
            }

    }
}

I used a converter to get this:

package hello

//remove if not needed
import scala.collection.JavaConversions._

object HelloWorldApp {

  def main(args: Array[String]): Unit = {
    val toDates: SortedMap[Long, Long] = new TreeMap[Long, Long]()
    val iterLong: Iterator[Long] = toDates.keySet.iterator()
    while (iterLong.hasNext) println("TEST")
  }

}

The problem is the iterator() call really is not liked in scala (which I am executing through spark)

<console>:190: error: type mismatch;
 found   : java.util.Iterator[Long]
 required: scala.collection.Iterator[Long]
                         val iterLong: Iterator[Long] = toDates.keySet.iterator()

I understand what he error is saying basically. Though, I am not sure how to force the type of scala.collection on the keySet.iterator() call.

I did do this:

    val iterLong: scala.collection.Iterator[Long] = toDates.keySet.iterator()

To no avail What else can I add to have that iterator come back and work correclty in the loop?

2
  • 1
    toDates.keys.toIterator Commented Oct 11, 2017 at 22:29
  • 1
    Recommended way is to import JavaConverters._ and call .asScala when needed. See here Commented Oct 11, 2017 at 22:30

1 Answer 1

3

You can either convert from Java to Scala, or you can just work with the Java one directly.

Converting

Add this import

import collection.JavaConverters._

and then use the new asJava/asScala methods to convert collections:

val iterLong: Iterator[Long] = (...).toScala

Directly Using Java Types

When doing interop with java collections, it’s common to do

import java.{ util => ju }

So that Java collection types can be accesed via ju.??? without fear of naming conflicts. With the above import in scope, write

val iterLong: ju.Iterator[Long] = ... // or let type inference do it for you

and use the Java API

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.