I want to find a way to define a new method in some existing class in scala.
For example, I think the method asInstanceOf[T]has a name too long, I want to replace itas[T].
A direct approach may be as follows:
class WrappedAny(val a: Any) {
def as[T] = a.asInstanceOf[T]
}
implicit def wrappingAny(a: Any): WrappedAny = new WrappedAny(a)
Is there a more natural way with less code?
Also, when I try to do this, a strange thing arises:
scala> class A
defined class A
scala> implicit def toA(x: Any): A = x
toA: (x: Any)A
scala> toA(1)
And the console is hanging. It seems that the toA(Any)type checking phase should not go through, and it cannot, unless it is implied. And incorporating all the code into external source code can lead to the same problem. How did this happen? Is this a compiler error (version 2.8.0)?
source
share