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]?

Edit
Report