I created one function:
def ignore(f: Unit => Unit) = {
userDisabled = true
f
userDisabled = false
}
Now I get a warning:
a pure expression does nothing in statement position; you may be omitting necessary parentheses
When I add the parentheses, and write f()
, I get:
Adaptation of argument list by inserting () has been deprecated: this is unlikely to be what you want. signature: Function1.apply(v1: T1): R given arguments: after adaptation: Function1((): Unit)
What am I doing wrong?
You probably wanted to declare ignore
as
def ignore(f: () => Unit) = {
userDisabled = true
f()
userDisabled = false
}
With is function with 0 arity that returns Unit
Currently you have a 1 arg function that expects parameter of type Unit
. There is only one value with such type and it is ()
.
When you simply say f
, you do nothing, you don't call the function, hence the first warning. It is as if you just put:
userEnabled = true
42
userEnabled = false
When you say f()
you are not passing an argument to a function that expects one. Scala can put there Unit
for you, but it is deprecated, hence the second warning. You should call it as f(())
.
Another option could be call by name parameter
def ignore(f: => Unit) = {
userDisabled = true
f
userDisabled = false
}
in that case f
would cause side effects to happen each time you use it in the method body. This is the most common way of doing such thing as from caller perspective you can just say
ignore {
//code
}
instead of
ignore(() => {
//code
})
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