是静态的方法更可组合?

问题描述 投票:6回答:1

我有一个案例类叫做细胞,它具有运动细胞了无参数的方法,下,左,右...

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

感觉对了,这个操作起来应该是一个实例方法和被称为像这样:

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

然后,他们似乎更可组合。现在我可以绕过上,下,左,或右类型细胞=>细胞的参数。作为一个参数,以下实例方法是等效的值,因此不能作为一个函数被传递。

请参见以下两个注释行。

    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)

这是不好的做法,似乎有点臭。

scala lambda functional-programming static
1个回答
7
投票

斯卡拉使得它可以很容易地创建这样的情况下,lambda表达式:

move(_.up, team, nucleus)

你会发现,这比Cell.up更短。出于这个原因,它似乎没有必要在同伴也定义它们。

© www.soinside.com 2019 - 2024. All rights reserved.