macaroneigh
macaroneigh

Reputation: 3

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.

  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.

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.

Upvotes: 0

Views: 673

Answers (1)

Oleg Zinoviev
Oleg Zinoviev

Reputation: 559

Two things you need to do:

  1. Define in your class Point method +.
  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)
  }

Upvotes: 1

Related Questions