VinhBS
VinhBS

Reputation: 677

Method parameters with type like { def foo() }

While scanning through dispatch code base, I noticed a method is defined like this:

def pack[T](req: { def abort() }, result: => T): HttpPackage[T]

The type annotation { def abort() } looks very strange to me. I thought it might be some thing similar to duck typing, so I tried to pass with some thing like object bar { def foo = print("Hello, world!") } but the compiler still complain type mismatched. I googled but couldn't find any article mention about it.

Does anyone know about this type annotation and its use cases?

Thanks in advance.

Upvotes: 0

Views: 41

Answers (2)

Brian Agnew
Brian Agnew

Reputation: 272417

This is known as structural typing in the Scala world, or more colloquially, as duck typing. From the linked article:

def quacker(duck: {def quack(value: String): String}) {
  println (duck.quack("Quack"))
}

object BigDuck {
  def quack(value: String) = {
    value.toUpperCase
  }
}

quacker(BigDuck)

so your method above will accept any object that defines an abort() method, without implementing a specific interface/trait.

This is particularly useful for handling sets of classes that implement the same methods without a common interface/trait, and that you can't retrofit an interface over (e.g. from legacy apps/libraries)

Upvotes: 1

Lee
Lee

Reputation: 144206

This defines a parameter req with a structural type i.e. a type defined by the existence of certain members. In this case any type with an abort() method. You can't pass bar since it does not have such a method. If you defined it as:

object Bar {
   def abort(): Unit = print("Aborting!")
}

then you can pass it to pack:

pack(Bar, { ... })

Upvotes: 2

Related Questions