首页 > 解决方案 > 静态方法是否更可组合?

问题描述

我有一个名为Cell的案例类,它具有用于向上、向下、向左、向右移动单元格的无参数方法......

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

如果我想要这两个功能:

  1. 能够调用实例方法等函数
  2. 将函数用作其他函数的参数

看来我需要在伴生对象中静态定义方法,然后通过引用静态实现在类中定义它们

def up = Cell.up(this)

这是不是不好的做法,看起来有点臭。

标签: scalalambdafunctional-programmingstatic

解决方案


Scala 使得为这样的情况创建 lambdas 变得非常容易:

move(_.up, team, nucleus)

您会注意到它甚至比Cell.up. 出于这个原因,似乎没有必要在同伴中也定义它们。


推荐阅读