scala - 静态方法更可组合吗?

标签 scala lambda functional-programming static

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

 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/

    相关文章:

    c++ - 在 C++11 中使用 std::sort 和 lambda 函数对动态分配的多维 C 数组进行排序

    haskell 类型

    scala - 激活程序: Play Framework 2. 3.x : run vs.开始

    scala - Scala 中压平 'reactive' 调用结果

    c# - 连接表时 Linq Lambda 连接中断

    c++ - 来自 lambda 返回类型的模板化函数返回类型

    reflection - F# 函数可以在运行时专门化吗?

    javascript - 将嵌套数组中的值设置为 null 的功能方法

    scala - Scala future 是否支持非阻塞组合器,例如 firstNCompletedOf 和 firstNSuccCompletedOf?

    mongodb - 找不到针对Option [reactivemongo.bson.BSONObjectID]类型的Json解串器