This can be done using a converter wrapper:
import scala.collection.JavaConversions._
object ListConverter {
def toScalaList( jlist: java.util.List[AnyRef] ) = {
jlist.toList
}
}
which uses a implicit def asScalaBuffer in JavaConversions to return a Scala List. Then I can make the list injectable as:
<bean id="someItems" class="my.package.ListConverter" factory-method="toScalaList">
<constructor-arg type="java.util.List">
<util:list>
<ref bean="itemOne"/>
<ref bean="itemTwo"/>
</util:list>
</constructor-arg>
</bean>
I would like to find a cleaner way to do this
I can’t really use JavaConversions directly as a static factory call:
<bean id="someItems" class="scala.collection.JavaConversions" factory-method="asScalaBuffer">...</bean>
Since an implicit def is not really a static method in a Java universe.
P.S. To get it out of the way.. I know there are a lot of annotation driven config lovers, but I am not one of them, and that is not a solution I am looking for: I like my XML for Spring configs, and I like Spring to DI Scala
If you want to convert a
java.util.Listto a scalaListyou will have to provide your own conversion/factory method as no such method exists.JavaConversions.asScalaBuffercould be referenced exactly as you did in your XML definition as the Scala compiler generates static forwarder methods to theobjectinstance unless you tell it not to do so.The problem here is actually actually that this method returns a
scala.collection.mutable.Bufferwhich you still have to convert into aList.An alternative is to accept an instance of
Seq[A]to be injected. This would work asBuffer[A]extendsSeq[A]– but you have to be aware that you are injecting a wrapper around the (possibly mutable)java.util.List<A>instance then.