Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Scala 新关键字的异常使用_Scala - Fatal编程技术网

Scala 新关键字的异常使用

Scala 新关键字的异常使用,scala,Scala,多亏了这一点,我从Akos Krivach的评论中了解到了这一点 解决方案中的代码如下所示: 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").containsDupli

多亏了这一点,我从Akos Krivach的评论中了解到了这一点

解决方案中的代码如下所示:

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
关键字

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

干杯

这就是所谓的匿名类,在本例中,它扩展了AnyRef(又称对象)。当您需要滚动某个不想声明的类实例时,可以使用匿名类。编译器会为您生成乱七八糟的类名:

val x = new { def foo = println("foo") } 
x: AnyRef{def foo: Unit} = $anon$1@5bdc9a1a 
(请参见右侧的
$anon$1

事实上,您可能在Java中看到过类似的代码:

Comparator<Integer> comp = new Comparator<Integer>() {
  @Override
  public int compare(Integer integer, Integer integer2) {
    // ...
  }
}
定义方法(将隐式应用),该方法在调用时实例化的包装类或多或少等于以下内容:

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

new{…}
是否与
newanyref{…}
相同?
class Wrapper(private val s: List[T]) {
  def containsDuplicates = (s.distinct.size != s.size)
}