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 D开发者_运维问答oer. 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.)
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 often have "do nothing" objects, you can also have "do nothing" as the default implementation:
trait Doer {
def doit {}
}
val nothingDoer = new Doer
Basicly you want something like:
trait Doer {
def doit : Unit
}
You might consider looking at the type Option also.
精彩评论