Richard Searle

home

The magic of Scala type inferencing

06 Sep 2010

Considering mapping the Java XPathFunction into a standard Scala function represention. An implemention for a single parameter might be
abstract class One[T,R<:Object] extends Function1[T,R] with XPathFunction { 
      def evaluate(list:java.util.List[_]) = apply(list.get(0).asInstanceOf[T]) 
}
With the identity function defined as
object OneString extends One[String,String]{ 
    def apply(s:String)=s
}
The repl has the following result
scala> OneString.evaluate(Collections.singletonList("ddd"))                                                                                                  
res22: String = ddd
scala> val xf:XPathFunction = OneString
xf: javax.xml.xpath.XPathFunction = 
scala> xf.evaluate(Collections.singletonList("ddd"))       
res24: java.lang.Object = ddd
Note the types of the return values! The same function is being executed in each case, but via two aliases which have different associated types.