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.)
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.
=> 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).
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.
Since your return type is Unit, it's conventional not to use the =
val nothingDoer = new Doer {
def doit {}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With