首页 > 解决方案 > 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

如果两个函数都返回相同的数据类型,为什么会发生这种情况?

标签: scalafunctional-programmingfor-comprehension

解决方案


您的increment函数需要一个,List[Int]但在 for 理解中需要一段时间。这是因为在线上,你真的在​​说。如果你想让它编译,你希望你的代码看起来像这样:splitedIntsplited <- 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返回什么。


推荐阅读