njlarsson
njlarsson

Reputation: 2340

Scala syntax for do-nothing function?

Is there some standard way in Scala of specifying a function that does nothing, for example when implementing a trait? This works:

trait Doer {
  def doit
}

val nothingDoer = new Doer {
  def doit = { }
}

But perhaps there is some more congenial way of formulating nothingDoer?

Edit Some interesting answers have appeared, and I add a little to the question in response. First, it turns out that I could have used a default implementation in Doer. Good tip, but you don't always want that. Second, apparently a more idiomatic way of writing is:

val nothingDoer = new Doer {
  def doit { }
}

Third, although nobody suggested exactly that, I found that this also seems to work:

val nothingDoer = new Doer {
  def doit = Unit
}

Is this a good alternative?

(The ":Unit" that a few people suggested does not really add anything, I think.)

Upvotes: 10

Views: 14599

Answers (4)

Alexey Romanov
Alexey Romanov

Reputation: 170805

If you often have "do nothing" objects, you can also have "do nothing" as the default implementation:

trait Doer {
  def doit {}
}

val nothingDoer = new Doer

Upvotes: 2

peri4n
peri4n

Reputation: 1421

Basicly you want something like:

trait Doer {
    def doit : Unit
}

You might consider looking at the type Option also.

Upvotes: 0

Luigi Plinge
Luigi Plinge

Reputation: 51109

Since your return type is Unit, it's conventional not to use the =

val nothingDoer = new Doer {
  def doit {}
}

Upvotes: 13

Alois Cochard
Alois Cochard

Reputation: 9862

I don't know a more idiomatic way of doing this (I don't think there is a equivalent of Python 'pass' i.e.).

But you can use "Unit" to specify that a method return nothing in a Trait:

def doit: Unit

Upvotes: 2

Related Questions