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

Scala map以部分函数作为值

发布时间:2020-12-16 18:03:24 所属栏目:安全 来源:网络整理
导读:在 Twitter’s Scala school collections section中,它们显示带有部分函数的Map作为值: // timesTwo() was defined earlier.def timesTwo(i: Int): Int = i * 2Map("timesTwo" - timesTwo(_)) 如果我尝试用Scala 2.9.1和sbt编译它,我得到以下内容: [error]
在 Twitter’s Scala school collections section中,它们显示带有部分函数的Map作为值:

// timesTwo() was defined earlier.
def timesTwo(i: Int): Int = i * 2
Map("timesTwo" -> timesTwo(_))

如果我尝试用Scala 2.9.1和sbt编译它,我得到以下内容:

[error] ... missing parameter type for expanded function ((x$1) => "timesTwo".$minus$greater(timesTwo(x$1)))
[error]     Map("timesTwo" -> timesTwo(_))
[error]                                ^
[error] one error found

如果我添加参数类型:

Map("timesTwo" -> timesTwo(_: Int))

然后我得到以下编译器错误:

[error] ... type mismatch;
[error]  found   : Int => (java.lang.String,Int)
[error]  required: (?,?)
[error]     Map("timesTwo" -> timesTwo(_: Int))
[error]                    ^
[error] one error found

我很难过.我错过了什么?

解决方法

它认为你想这样做:

Map((x: Int) => "timesTwo".->timesTwo(x))

如果你想要这个:

Map("timesTwo" -> { (x: Int) => timesTwo(x) })

这样可行:

Map( ("timesTwo",timesTwo(_)) )
 Map("timesTwo" -> { timesTwo(_) })

请注意,这不是通常的错误,请参阅

> https://stackoverflow.com/a/7695459/257449.
> Scala underscore – ERROR: missing parameter type for expanded function

(可能更多)

(编辑:李大同)

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

    推荐文章
      热点阅读