简体   繁体   中英

Scala and Java data structures

I'm new to Scala and have imported an external Java (nmap4J) library that returns an object called:

class org.nmap4j.data.nmaprun.Verbose
  • How do I determine what the object type is in scala?
  • How would I then convert it to something thats usable in Scala?

I'm assuming I would ned to use the Scala Java Conversions, but I'm a little confused as where to start.

http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.JavaConversions

You can use it just like you'd use it in Java, and it's type doesn't change: it's org.nmap4j.data.nmaprun.Verbose .

Conversions and Converters are intended to transform a Java standard library collection into a Scala standard library collection and vice versa. Generally speaking, if you have a Java collection that is not from the standard library, there's likely some reason for it to be different, and converting it to Scala would defy its purpose.

type conversion

Lets say you have an unknown Object (scala Any / AnyRef ) and you think it is a class of Verbose:

import org.nmap4j.data.nmaprun.Verbose

def checkObj(in: Any) {
  in match {
    case v: Verbose =>
      // do something with v

    case _ =>
      // do error handling
}

This is the scala way of doing isInstanceOf / asInstanceOf . Almost always you can treat a java class like a scala class.

list conversion

If your framework gives you java collections, you import, as you said correctly, java conversions.

import scala.collection.JavaConversions._

def doSomething(list: java.util.List[Any]) {
  // map is now possible due to the implicit conversion of list
  list.map(el => doStuff(el))

  // other methods
  list.toSeq
  list.foreach(println)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM