我有一个名为 的案例类手机 它具有无参数的方法来向上、向下、向左、向右移动单元格...
case class Cell(topLeft: Coordinate, botRight: Coordinate) {
def up: Cell = {
Cell(
Coordinate(topLeft.x + 0, topLeft.y - 1)
, Coordinate(botRight.x + 0, botRight.y - 1))
}
}
感觉这个 up 操作应该是一个实例方法并像这样调用:
val cell = Cell(x,y)
cell.up
但是,如果我使这些操作属于一个伴随对象的静态函数,像这样,
object Cell{
def up(cell: Cell): Cell = {
Cell(
Coordinate(cell.topLeft.x + 0, cell.topLeft.y - 1)
, Coordinate(cell.botRight.x + 0, cell.botRight.y - 1))
}
...
}
那么它们似乎更易于组合。现在我可以向上、向下、向左或向右传递作为 Cell => Cell 类型的参数。作为无参数实例方法,它相当于一个值,因此不能作为函数传递。
请参阅下面的两个注释行。
private def move(move: Cell => Cell, team: Team, nucleus: Coordinate): Team = {
val (mover, others) = team.cells.partition(_.nucleus == Some(nucleus))
val newCell = move(mover.head) // Works using STATIC move
val newCell = mover.head.move // Doesn't Work (needs .up, .down etc...)
if(mover.nonEmpty){
if(isValidCellState(newCell)) {
Team(newCell :: others)
}else{
throw new BadMoveException("Invalid move from this position")
}
}else{
throw new BadMoveException("You didn't select a cell to move")
}
}
如果我想要这两个功能:
似乎我需要在伴随对象中静态定义方法,然后通过引用静态实现在类中定义它们
def up = Cell.up(this)
这是不好的做法,似乎有点臭。
最佳答案
Scala 使得为这样的情况创建 lambda 变得非常容易:
move(_.up, team, nucleus)
你会注意到这比
Cell.up
还要短.出于这个原因,似乎没有必要在同伴中也定义它们。
关于scala - 静态方法更可组合吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54544847/