new 关键字的异常使用 [英] Unusual use of the new keyword

查看:45
本文介绍了new 关键字的异常使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢这个线程,我从 Akos Krivach 的评论中关注了这个 link.

Thanks to this thread, I followed this link from Akos Krivach's comment.

解决方案中的代码如下:

The code in the solution is as follow:

implicit def enhanceWithContainsDuplicates[T](s:List[T]) = new {
  def containsDuplicates = (s.distinct.size != s.size)
}

assert(List(1,2,2,3).containsDuplicates)
assert(!List("a","b","c").containsDuplicates)

我从未见过在此上下文中使用的 new 关键字.

I have never seen that new keyword used in this context.

谁能告诉我它是如何工作的?这个模式有名字吗?

Anyone can enlighten me on how it works? Is there a name for this pattern?

干杯

推荐答案

这就是所谓的匿名类,它在这种情况下扩展了 AnyRef(又名对象).当您需要滚动某些不想声明的类实例时,将使用匿名类.编译器为你生成乱七八糟的类名:

It's so called anonymous class which in this case extends AnyRef (aka Object). Anonymous classes are used when you need to roll some instance of class, which you don't want to declare. Compiler generates gibberish class name for you:

val x = new { def foo = println("foo") } 
x: AnyRef{def foo: Unit} = $anon$1@5bdc9a1a 

(看,右边的 $anon$1)

事实上,你可能已经在 J​​ava 中看到过类似的代码:

In fact, you may have seen similar code in Java:

Comparator<Integer> comp = new Comparator<Integer>() {
  @Override
  public int compare(Integer integer, Integer integer2) {
    // ...
  }
}

这个特殊的代码

implicit def enhanceWithContainsDuplicates[T](s:List[T]) = new {
  def containsDuplicates = (s.distinct.size != s.size)
}

定义方法(将隐式应用),当调用时,实例化包装类或多或少等于以下内容:

Defines method (which will be applied implicitly), that, when called, instantiates wrapper class more or less equal to the following:

class Wrapper(private val s: List[T]) {
  def containsDuplicates = (s.distinct.size != s.size)
}  

这篇关于new 关键字的异常使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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