Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala syntax for do-nothing function?

Tags:

scala

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.)

like image 299
njlarsson Avatar asked Sep 05 '11 11:09

njlarsson


People also ask

What is a do nothing function?

A function that does nothing (yet) is an indicator that something should be done, but hasn't been implemented yet. Follow this answer to receive notifications. answered Jun 27, 2016 at 13:42. Ivan Rubinson.

What does => mean in Scala?

=> is the "function arrow". It is used both in function type signatures as well as anonymous function terms. () => Unit is a shorthand for Function0[Unit] , which is the type of functions which take no arguments and return nothing useful (like void in other languages).

What is the syntax of defining method in Scala?

Syntax. def functionName ([list of parameters]) : [return type] = { function body return [expr] } Here, return type could be any valid Scala data type and list of parameters will be a list of variables separated by comma and list of parameters and return type are optional.


2 Answers

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

val nothingDoer = new Doer {
  def doit {}
}
like image 70
Luigi Plinge Avatar answered Sep 22 '22 17:09

Luigi Plinge


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
like image 30
Alois Cochard Avatar answered Sep 21 '22 17:09

Alois Cochard