Scala 类型不匹配,无法解决问题

Scala Type Mismatch, Can't Resolve the Problem

所以,对于一个项目,我正在尝试让游戏生成的块移动的特定部分。所有坐标都存储在一个列表中,通过“x”和“y”值我应该能够将坐标相加,进而使块移动。

  def movement(move: Point): Unit = {
    val newList: List[Point] = placed
    val xx = move.x; val yy = move.y
    for (i <- newList.indices) newList(i) += Point(xx, yy)
  }

这里的“placed”是放置所有坐标的List。 “点”类型指的是“x”和“y”值。

这里的问题是,当我尝试将新值添加到坐标时,它显示:

Type mismatch. Required: String, found: Point

我觉得这很奇怪,因为我的列表不是以字符串类型启动的。有什么办法可以解决这个问题吗?

非常感谢。

添加了之前项目的示例:

  var playAnimal: List[Point] = List(Point(2,0), Point(1,0), Point(0,0))

  def checkForWrap (p: Point) : Point = {
    var x = p.x; var y = p.y
    x = if (x < 0) nrColumns - 1 else if (x > nrColumns - 1) 0 else x
    y = if (y < 0) nrRows - 1 else if (y > nrRows - 1) 0 else y
    Point(x, y)
  }

  def moveAnimal(): Unit = {
    if(!gameOver) {
      def newAnimalFront: Point = {
        val newHead: Point = currentDir match {
          case East()  => playAnimal.head + Point( 1,  0)
          case West()  => playAnimal.head + Point(-1,  0)
          case North() => playAnimal.head + Point( 0, -1)
          case South() => playAnimal.head + Point( 0,  1) 
        }
        checkForWrap(newHead)
      }
      playAnimal = newAnimalFront +: playAnimal.init
    }
  }

但是,此方法在我当前的项目中显示字符串不匹配。

您需要做两件事:

  1. 在您的 class Point 方法中定义 +
  2. 避免突变(这取决于你,但你的代码变得更具可读性)。

那你可以这样写:

  def main(args: Array[String]): Unit = {
    val placed: List[Point] = List(Point(0, 0), Point(1, 1))
    println(placed.mkString) // Point(0,0)Point(1,1)
    val moved = movement(Point(2, 2), placed)
    println(moved.mkString) //Point(2,2)Point(3,3)
  }
  def movement(move: Point, placed: List[Point]): List[Point] = {
    // here you create new list and don't mutate the old one
    placed.map(p => p + move)
  }
  case class Point(x: Int, y: Int) {
    def +(p: Point) = Point(x + p.x, y + p.y)
  }