3

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)

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?

Cheers

Community
  • 1
  • 1
ccheneson
  • 49,072
  • 8
  • 63
  • 68

1 Answers1

6

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 

(see, that $anon$1 to the right)

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

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

This particular code

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)
}  
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228