scala和java之间的隐式转换

用scala的时候避免不了会和java进行交互。经常用到的就是java和scala之间的数据结构转换。如下

val skills = JavaConversions.asScalaBuffer(counselorExtInfo.getSkills)

周末有空看源码,才发现,有隐式转换可以用。可以直接import就可以了。

class UsersService extends grizzled.slf4j.Logging {
  import scala.collection.JavaConversions._

就可以直接使用scala的类型了,因为有了隐式转换的存在,如下:

val skills: mutable.Buffer[CounselorSkillCategory] = counselorExtInfo.getSkills

JavaConversions类的源码如下,集成了WrapAsScala和 WrapAsJava两个特性

package scala
package collection

import convert._

/**   A collection of implicit conversions supporting interoperability between
 *    Scala and Java collections.
 *
 *    The following conversions are supported:
 *{{{
 *    scala.collection.Iterable <=> java.lang.Iterable
 *    scala.collection.Iterable <=> java.util.Collection
 *    scala.collection.Iterator <=> java.util.{ Iterator, Enumeration }
 *    scala.collection.mutable.Buffer <=> java.util.List
 *    scala.collection.mutable.Set <=> java.util.Set
 *    scala.collection.mutable.Map <=> java.util.{ Map, Dictionary }
 *    scala.collection.concurrent.Map <=> java.util.concurrent.ConcurrentMap
 *}}}
 *    In all cases, converting from a source type to a target type and back
 *    again will return the original source object, eg.
 *
 *{{{
 *    import scala.collection.JavaConversions._
 *
 *    val sl = new scala.collection.mutable.ListBuffer[Int]
 *    val jl : java.util.List[Int] = sl
 *    val sl2 : scala.collection.mutable.Buffer[Int] = jl
 *    assert(sl eq sl2)
 *}}}
 *  In addition, the following one way conversions are provided:
 *
 *{{{
 *    scala.collection.Seq         => java.util.List
 *    scala.collection.mutable.Seq => java.util.List
 *    scala.collection.Set         => java.util.Set
 *    scala.collection.Map         => java.util.Map
 *    java.util.Properties         => scala.collection.mutable.Map[String, String]
 *}}}
 *
 *  @author Miles Sabin
 *  @author Martin Odersky
 *  @since  2.8
 */
object JavaConversions extends WrapAsScala with WrapAsJava


评论