java - 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
}
}
但是,此方法在我当前的项目中显示字符串不匹配。
解决方案
你需要做两件事:
- 在您的类
Point
方法中定义+
。 - 避免突变(这取决于您,但您的代码变得更具可读性)。
然后你可以这样写:
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)
}
推荐阅读
- javascript - 悬停时的多个图像过渡
- sql - 内存表中的 SQL 一直在增长,尽管它已被清空
- c++ - 基于 SFINAE 的特征来确定是否支持运算符 +
- swift - Swift:似乎无法将 placeClient.currentPlace 的结果位置存储为类属性以在其他地方使用
- firebase - FirebaseFunctions.getinstance() 未完成
- node.js - 外部链接在 Docker Compose 中不起作用
- postgresql - 什么类型的索引最适合低选择性列
- android - Android - 你应该如何管理多个模块?清单、等级等
- javascript - 导航()抛出错误 - 反应原生
- dictionary - Julia 中 Dict 和 Base.Iterators.Pairs 之间的区别