将方法注入现有类 [英] Inject methods into existing classes

查看:43
本文介绍了将方法注入现有类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想想办法在 Scala 中的某个现有类中定义一个新方法.

I want to come out a way to define a new method in some existing class in scala.

比如我觉得asInstanceOf[T]方法的名字太长,我想用as[T]代替.

For example, I think the asInstanceOf[T] method has too long a name, I want to replace it with as[T].

直接的方法可以是:

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, a strange thing happens when I try this:

scala> class A

defined class A

scala> implicit def toA(x: Any): A = x

toA: (x: Any)A

scala> toA(1)

控制台挂了.似乎 toA(Any) 不应该通过类型检查阶段,并且当它不是隐式时就不能.而把所有的代码放到一个外部源代码中也会产生同样的问题.这怎么发生的?是编译器的bug(2.8.0版)吗?

And the console hang. It seems that toA(Any) should not pass the type checking phase, and it can't when it's not implicit. And putting all the code into a external source code can produce the same problem. How did this happen? Is it a bug of the compiler(version 2.8.0)?

推荐答案

你拉皮条 Any 的方法在技术上没有问题,尽管我认为这通常是不明智的.同样,asInstanceOfisInstanceOf 的命名如此冗长也是有原因的;这是为了阻止你使用它们!几乎可以肯定,有一种更好的、静态类型安全的方法可以做您想做的任何事情.

There's nothing technically wrong with your approach to pimping Any, although I think it's generally ill-advised. Likewise, there's a reason asInstanceOf and isInstanceOf are so verbosely named; it's to discourage you from using them! There's almost certainly a better, statically type-safe way to do whatever you're trying to do.

关于导致控制台挂起的示例:toA 的声明类型是 Any =>A,但您已将其结果定义为 x,其类型为 Any,而不是 A.这怎么可能编译?好吧,请记住,当发生明显的类型错误时,编译器会四处寻找任何可用的隐式转换来解决问题.在这种情况下,它需要一个隐式转换 Any =>;A...并找到一个:toA!所以 toA 类型检查的原因是因为编译器隐式地将其重新定义为:

Regarding the example which causes your console to hang: the declared type of toA is Any => A, yet you've defined its result as x, which has type Any, not A. How can this possibly compile? Well, remember that when an apparent type error occurs, the compiler looks around for any available implicit conversions to resolve the problem. In this case, it needs an implicit conversion Any => A... and finds one: toA! So the reason toA type checks is because the compiler is implicitly redefining it as:

implicit def toA(x: Any): A = toA(x)

...当您尝试使用它时,这当然会导致无限递归.

... which of course results in infinite recursion when you try to use it.

这篇关于将方法注入现有类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆