以下代码显示类型不匹配错误:
def f(arr:List[Int]): List[Int] =
for(num <- 0 to arr.length-1; if num % 2 == 1) yield arr(num)
Run Code Online (Sandbox Code Playgroud)
据说它找到了IndexedSeq而不是List。以下作品:
def f(arr:List[Int]): List[Int] =
for(num <- (0 to arr.length-1).toList; if num % 2 == 1) yield arr(num)
Run Code Online (Sandbox Code Playgroud)
我i <- a to b之前在for循环中使用过,但之前没有看到此错误。有人可以解释为什么i <- a to b不能在此处使用该格式吗?
因为0 to arr.length-1return type是:IndexedSeq[Int],所以执行for yield时也会产生IndexedSeq[Int]type的结果。
正确的函数定义:
def f(arr:List[Int]):IndexedSeq[Int] = for( num <- 0 to arr.length-1 if num%2==1) yield arr(num)
Run Code Online (Sandbox Code Playgroud)
和
for( num <- 0 to arr.length-1 if num%2==1) yield arr(num)
Run Code Online (Sandbox Code Playgroud)
将转换为:
scala> def f(arr:List[Int]) = (0 to arr.length-1).filter(i => i%2==1).map(i => arr(i))
f: (arr: List[Int])scala.collection.immutable.IndexedSeq[Int]
Run Code Online (Sandbox Code Playgroud)
这样我们就可以看到返回类型是由0 to arr.length-1类型决定的。
并且(0 to arr.length-1).toList将返回IndexedSeq[int]类型更改为List[Int]type,因此for yield将生成类型为的结果List[Int]。
| 归档时间: |
|
| 查看次数: |
1850 次 |
| 最近记录: |