加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 在函数中执行函数时发出警告

发布时间:2020-12-16 18:23:13 所属栏目:安全 来源:网络整理
导读:我创建了一个函数: def ignore(f: Unit = Unit) = { userDisabled = true f userDisabled = false} 现在我收到警告: a pure expression does nothing in statement position; you may be omitting necessary parentheses 当我添加括号,并写入f()时,我得到
我创建了一个函数:

def ignore(f: Unit => Unit) = {
    userDisabled = true
    f
    userDisabled = false
}

现在我收到警告:

a pure expression does nothing in statement position; you may be omitting necessary parentheses

当我添加括号,并写入f()时,我得到:

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)

我究竟做错了什么?

解决方法

您可能想要将ignore声明为

def ignore(f: () => Unit) = {
    userDisabled = true
    f()
    userDisabled = false
}

带有返回Unit的0 arity函数

目前你有一个1 arg函数,它需要Unit类型的参数.这种类型只有一个值,它是().

当你简单地说f,你什么都不做,你不调用函数,因此第一个警告.就像你刚刚放:

userEnabled = true
42
userEnabled = false

当你说f()时,你没有将参数传递给期望它的函数. Scala可以为你提供Unit,但它已被弃用,因此是第二次警告.你应该把它称为f(()).

另一种选择可以是通过名称参数调用

def ignore(f: => Unit) = {
    userDisabled = true
    f
    userDisabled = false
}

在这种情况下,每次在方法体中使用时,f都会导致副作用.这是执行此类操作的最常见方式,从调用者的角度来看,您可以这么说

ignore {
  //code
}

代替

ignore(() => {
  //code
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读