简体   繁体   English

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

[英]Scala Type Mismatch, Can't Resolve the Problem

So, for a project, I'm trying to make a specific piece of a game generated block move.所以,对于一个项目,我试图让游戏生成的块移动的特定部分。 All coordinates are stored in a List and through "x" and "y" values I should be able to add up to the coordinates, and in turn make the block move.所有坐标都存储在一个列表中,通过“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)
  }

Here, "placed" is the List where all coordinates are placed.此处,“已放置”是放置所有坐标的列表。 The "Point" type refers to the "x" and "y" values. “Point”类型指的是“x”和“y”值。

The problem here is that when I try to add the new values to the coordinate, it says:这里的问题是,当我尝试将新值添加到坐标时,它说:

Type mismatch.类型不匹配。 Required: String, found: Point必需:字符串,找到:点

I found this strange, since my list is not initiated with the string type.我发现这很奇怪,因为我的列表不是用字符串类型启动的。 Is there any way to work around this problem?有没有办法解决这个问题?

Many thanks.非常感谢。

Added example of previous project:添加了以前项目的示例:

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

This method, however, is displaying the String mismatch in my current project.但是,此方法在我当前的项目中显示字符串不匹配。

Two things you need to do:你需要做的两件事:

  1. Define in your class Point method + .在您的类Point方法中定义+
  2. Avoid mutations(it's up to you but your code becomes more readable).避免突变(这取决于您,但您的代码变得更具可读性)。

Then you can write smth like this:然后你可以这样写:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM