scala - Scala-不为理解而编译
问题描述
我正在尝试运行以下代码:
def split(input: Int): List[Int] = {
val inputAsString = input.toString
val inputAsStringList = inputAsString.split("").toList
inputAsStringList.map(_.toInt).reverse
}
split(3122)
def increment(list: List[Int]): List[Int] = {
def loop(multiplier: Int, result: List[Int], list: List[Int]): List[Int] = list match {
case x :: xs =>
val newList = (x * multiplier) :: result
loop(multiplier * 10, newList, xs)
case Nil => result
}
loop(1, List(), list)
}
val result: List[Int] = for {
splited <- split(3122)
incremented <- increment(splited)
} yield incremented
但是该行incremented <- increment(splited)
给出以下错误:
类型不匹配,预期:List[Int],实际:Int
如果两个函数都返回相同的数据类型,为什么会发生这种情况?
解决方案
您的increment
函数需要一个,List[Int]
但在 for 理解中需要一段时间。这是因为在线上,你真的在说。如果你想让它编译,你希望你的代码看起来像这样:splited
Int
splited <- split(3122)
for every x: Int in split(y): List[Int]
val result
...
val splited = split(3122)
val result: List[Int] = for {
incremented <- increment(splited)
} yield incremented
这返回result: List[Int] = List(2)
。无论您是否期望这是另一回事 - 我不确定您期望increment
返回什么。
推荐阅读
- typescript - 将对象中的子键限制为父键的子类型
- html - 如何垂直对齐导航元素中的列表项?
- arduino - Sim800l 收到短信但显示未知号码,硬件很好
- powerbi - 如何在 Power Query 编辑器中按组求和?
- facebook - 使用 facepager 从 facebook 中提取喜欢和喜欢
- google-cloud-platform - BigQuery - 将查询复制到新表中
- c# - C# 程序未连接到数据库 (freesqldatabase.com)
- docker-compose - `无法访问'XXX':无法解析主机`Gitlab CI/CD管道
- reactjs - 在异步函数中反应 useEffect
- java - 类继承和泛型类型