I don't like Scala isInstanceOf and asInstanceOf methods - they are long and asInstanceOf can throw exception so we need to use it in couple. Better way is to use pattern matching: Scala: How do I cast a variable? but for really simple operations it can be relatively long too. In C# we have 'is' and 'as' operators so I wanted to implement implicit definition with this in Scala. My code look like this:
scala> class TypeCast(x:Any){
| def is[T](t:Class[T]) = t.isInstance(x)
| def as[T](t:Class[T]):Option[T] = if(t.isInstance(x)) Option(t.cast(x)) else None
| }
defined class TypeCast
scala> implicit def TypeCastID(x:Any)=new TypeCast(x)
TypeCastID: (x: Any)TypeCast
scala> 123 as classOf[String]
res14: Option[String] = None
scala> "asd" as classOf[String]
res15: Option[String] = Some(asd)
It has one advantage - implement null-object pattern but also have disadvantages:
need to use classOf[T] operator - it's too long
overhead connected with implicit def for such simple operation
so there is no practical reason to use it. I would like to know is there any way to implement this without need to use classOf[T]?
Well you could shorten it down inside the def you made in the TypeCast class. So instead of feeding it a parameter you could just rely on the type. This would shorten it down a lot. As an example this could look something like:
class TypeCast(x : Any) {
def is[T : Manifest] = manifest.erasure.isInstance(x)
def as[T : Manifest] : Option[T] = if (manifest.erasure.isInstance(x)) Some(x.asInstanceOf[T]) else None
}
Future calls could look like:
scala> 123.as[String]
res0: Option[String] = Some(123)
scala> class A; class B extends A
defined class A
defined class B
scala> new B
res1: B
scala> res1.is[Int]
res2: Boolean = false
scala> res1.as[Int]
res3: Option[Int] = None
Update: I added Manifests to avoid type-check errors
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With