1

Im trying to iterate over a java util.iterator with Scala but am having trouble with casting the objects to the correct class.

I get the error:

type mismatch; found: java.util.Iterator[?0] where type ?0 
required : java.util.iterator[net.percederberg.mibble.MibSymbol]
  val iter:util.Iterator[MibSymbol] == mib_obj.getAllSymbols.iterator()

the code looks like following:

import java.io.File
import java.util
import net.percederberg.mibble._
import scala.collection.immutable.HashMap
import scala.collection.JavaConversions._

object Bacon {
  def main(args:Array[String]) {
    println("hello")
    val mib_obj:Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
    val iter:util.Iterator[MibSymbol] = mib_obj.getAllSymbols.iterator()
    while(iter.hasNext()) {
      var obj:MibSymbol = iter.next()
      println(obj.getName())
    }

  }
  def loadMib(file: File): Mib = {
    var loader: MibLoader = new MibLoader()
    loader.addDir(file.getParentFile())
    return loader.load(file)
  }


}
2
  • Looks like getAllSymbols.iterator() does not return an Iterator of MibSymbol. What's the signature of getAllSymbols? Commented Apr 2, 2015 at 13:55
  • Not sure. According to the documentation its 'public java.util.Collection getAllSymbols()' Its a public library Commented Apr 2, 2015 at 14:07

1 Answer 1

2

Use an explicit typecast asInstanceOf[Iterator[MibSymbol]]:

  def main(args: Array[String]) {
    println("hello")
    val mib_obj: Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
    val x = mib_obj.getAllSymbols.iterator()
    val iter: util.Iterator[MibSymbol] = x.asInstanceOf[Iterator[MibSymbol]]
    while (iter.hasNext()) {
      var obj: MibSymbol = iter.next()
      println(obj.getName())
    }
  }

  def loadMib(file: File): Mib = {
    var loader: MibLoader = new MibLoader()
    loader.addDir(file.getParentFile())
    return loader.load(file)
  }

NOTE: In absence of runtime type information, this may fail.

EDIT1: You can also use a for comprehension:

val mib_obj: Mib = loadMib(new File("/Users/tjones24/dev/mibs/DOCS-IF-MIB.my"))
for ( obj <- mib_obj.getAllSymbols) {
  println(obj.asInstanceOf[MibSymbol].getName())
}

import scala.collection.JavaConversions._ does all the magic for you. You only need to ensure that the types are correct.

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.