scala - 静态方法是否更可组合?
问题描述
我有一个名为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")
}
}
如果我想要这两个功能:
- 能够调用实例方法等函数
- 将函数用作其他函数的参数
看来我需要在伴生对象中静态定义方法,然后通过引用静态实现在类中定义它们
def up = Cell.up(this)
这是不是不好的做法,看起来有点臭。
解决方案
Scala 使得为这样的情况创建 lambdas 变得非常容易:
move(_.up, team, nucleus)
您会注意到它甚至比Cell.up
. 出于这个原因,似乎没有必要在同伴中也定义它们。
推荐阅读
- selenium - 如何在没有 Selenium 的情况下制作自动化的帖子作者
- angular - 当某些失败无关紧要时如何处理多个可观察对象?
- excel - Excel 文件另存为 CSV 时总金额相差 1c
- python - 在包缓存中发现没有条目的 Conda 管理的包
- c# - 由于我的 API 返回不同的属性,我应该使用动态对象吗?
- django - 在 curl 命令中添加自定义 id 参数
- node.js - 在 Firebase 中构建用户的收藏夹并将数据写入其中
- python - 如何在 python 中找到数据框列的日志?
- string - 方案 - 如何读取 cond 中的字符串
- c - 从队列中删除所有项目