CodeMan
CodeMan

Reputation: 139

What does curly bracket after a trait definition name mean in scala?

While using Future I have seen people use

Future{
      Thread sleep 500
      promise success "You've just completed the promise with me in it!"
 }

Looking at the definition of Future, I can see that Future is a trait

But when I make my own trait, Example:

trait t{}
def main(args: Array[String]): Unit = {
    t{
        println("Test")
    }
}

It does not compile. Why?

Upvotes: 0

Views: 73

Answers (2)

C4stor
C4stor

Reputation: 8026

The syntax for Future you describe comes from the trait companion object.

This object has the following method :

  def apply[T](body: =>T)(implicit @deprecatedName('execctx) executor: ExecutionContext): Future[T] =
    unit.map(_ => body)

The accepted argument being a function returning a T, it's perfectly idiomatic to pass it via the form you see, which is a bracketed code block.

This being said, you can kind of instantiate your traits (by creating anonymous subclasses of them), the following compile :

trait t {}

object MyApp extends App {
  new t {
    println("Test")
  }
}

I would not recommend it as a general good practice though, but it has its uses.

Upvotes: 2

Dionysis Nt.
Dionysis Nt.

Reputation: 955

when you write Future{ /*your code*/ } then the apply method of the companion object of Future is called.

the signature of the Future's apply method is the following

def apply[T](body:=>T)

You can see that the apply method is called when you do ctrl+click or cmd+click on the Future in an IDE such as InteliJ.

Your trait t does not have an apply. Therefore that piece of code does not compile.

trait t{}
object t{
  apply[T](body:=>T){}
}

Upvotes: 5

Related Questions