首页 > 解决方案 > Scala 类型不匹配,无法解决问题

问题描述

所以,对于一个项目,我正在尝试制作一个特定的游戏生成块移动。所有坐标都存储在一个列表中,通过“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)
  }

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

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

类型不匹配。必需:字符串,找到:点

我发现这很奇怪,因为我的列表不是以字符串类型启动的。有没有办法解决这个问题?

非常感谢。

添加了以前项目的示例:

  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
    }
  }

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

标签: javastringscalamismatch

解决方案


你需要做两件事:

  1. 在您的类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)
  }

推荐阅读