通过调用 toSet 缺少参数类型错误? [英] Missing parameter type error by calling toSet?

查看:35
本文介绍了通过调用 toSet 缺少参数类型错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试从字符列表中生成映射到其频率的唯一字符列表 - 例如类似:

Trying to generate, from a list of chars, a list of unique chars mapped to their frequency - e.g. something like:

List('a','b','a') -> List(('a',2), ('b',1))

所以,只是在控制台中乱搞,这是有效的:

So, just mucking around in the console, this works:

val l = List('a', 'b', 'c', 'b', 'c', 'a')       
val s = l.toSet                                  
s.map(i => (i, l.filter(x => x == i).size))

但是,仅仅结合最后两行来缩短不是吗?

but, shortening by just combining the last 2 lines doesn't?

l.toSet.map(i => (i, l.filter(x => x == i).size)) 

给出错误缺少参数类型".

gives the error "missing parameter type".

谁能解释为什么 Scala 会抱怨这种语法?

Can someone explain why Scala complains about this syntax?

推荐答案

当你说 val s = l.toSet 时,编译器认为 toSet 的唯一合理类型是 Char——这是最具体的选择.然后,假设s是一组Char,编译器意识到映射必须来自一个Char.

When you say val s = l.toSet the compiler figures that the only sensible type for toSet is Char--that's the most specific choice. Then, given that s is a set of Char, the compiler realizes that the map must be from a Char.

但在第二种情况下,它不判断 toSet 中元素的类型是什么.它可能是 Char,但 AnyVal 也可以,就像 Any 一样.

But in the second case, it withholds judgment on what the type of elements in toSet is. It might be Char, but AnyVal would also work, as would Any.

l.toSet.map((i: Any) => (i, l.filter(x => x == i).size))

通常规则是编译器应该选择最具体的值.但是由于函数的参数是逆变的,当它们将 Any 作为参数时,它们是最具体的,因此编译器无法决定.可能存在打破平局的规则(更喜欢早期假设"),但没有实施.所以它需要你的帮助.

Normally the rule is that the compiler should pick the most specific value. But since functions are contravariant in their argument, they are most specific when they take an Any as an argument, so the compiler can't decide. There could exist a rule to break the tie ("prefer the early assumption"), but there isn't one implemented. So it asks for your help.

您可以在函数参数或 toSet 上提供类型以解决问题:

You can provide the type either on the function argument or on the toSet to fix the problem:

l.toSet.map((i: Char) => (i, l.filter(x => x == i).size))
l.toSet[Char].map(i => (i, l.filter(x => x == i).size))

这篇关于通过调用 toSet 缺少参数类型错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆