ZeroC Ice "tested throws" in Scala
ZeroC Ice for Java translates each Slice interface Simple
to (among other things) a proxy interface SimplePrx
and a proxy SimplePrxHelper
. If I have ObjectPrx
(basic interface for all proxies), I can check if it actually has an interface Simple
using a static method on SimplePrxHelper
:
val obj : Ice.ObjectPrx = ...; // Get a proxy from somewhere...
val simple : SimplePrx = SimplePrxHelper.checkedCast(obj);
if (simple != null)
// Object supports the Simple interface...
else
// Object is not of type Simple...
I wanted to write a method castTo
to replace the second line with
val simple = castTo[SimplePrx](obj)
or
val simple = castTo[SimplePrxHelper](obj)
As far as I can see, Scala's type system is not expressive enough for me to define castTo
. Is it correct?
a source to share
Should be able to do something with implicits, according to these lines:
object Casting {
trait Caster[A] {
def checkedCast(obj: ObjectPrx): Option[A]
}
def castTo[A](obj: ObjectPrx)(implicit caster: Caster[A]) =
caster.checkedCast(obj)
implicit object SimplePrxCaster extends Caster[SimplePrx] {
def checkedCast(obj: ObjectPrx) = Option(SimplePrxHelper.checkedCast(obj))
}
}
Then you just bring things into the scope where you want to use them:
package my.package
import Casting._
...
def whatever(prx: ObjectPrx) {
castTo[SimplePrx](prx) foreach (_.somethingSimple())
}
...
a source to share
You can get something like what you want with structured types:
def castTo[A](helper: { def checkedCast(o: Object): A })(o: Object) = {
helper.checkedCast(o)
}
class FooPrx { }
object FooPrxHelper {
def checkedCast(o: Object): FooPrx = o match {
case fp : FooPrx => fp
case _ => null
}
}
scala> val o: Object = new FooPrx
o: java.lang.Object = FooPrx@da8742
scala> val fp = castTo(FooPrxHelper)(o)
fp: FooPrx = FooPrx@da8742
a source to share