Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warnings while executing a function in a function

Tags:

scala

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?

like image 564
marmistrz Avatar asked Dec 14 '22 05:12

marmistrz


1 Answers

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
})
like image 187
Łukasz Avatar answered Dec 21 '22 10:12

Łukasz