Scala 偏函数组合
Scala Partial Function Composition
我正在尝试组合这两个函数:
// some case class that just holds data
case class DataMap( ... )
val action(i: Int)(data: DataMap): DataMap = { ... }
val tryFunction: DataMap => Try[DataMap] = Try.apply[DataMap]
val actionFunction: DataMap => DataMap = action(2)
tryFunction compose actionFunction
然后我得到这些错误:
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `apply _` or `apply(_)` instead of `apply`.
val tryFunction = Try.apply[DataMap]
^
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `action _` or `action(_)` instead of `action`.
val actionFunction = action(1)
^
谁能解释为什么会出现这个错误,以及如何避免它?
这是因为 Try.apply
的别名参数。这在这里有效:
import util.Try
case class DataMap()
def action(i: Int)(data: DataMap): DataMap = ???
val tryFunction: DataMap => Try[DataMap] = Try.apply[DataMap](_)
val actionFunction: DataMap => DataMap = action(2)
tryFunction compose actionFunction
action(2)
不需要 eta 扩展,因为 DataMap => DataMap
类型归属强制编译器期望函数为 return 类型,因此 action(2)
是自动转换为action(2)(_)
。
Try.apply[DataMap]
必须显式转换 eta,因为 apply[A]
的输入类型是 => A
(按名称),而不仅仅是 A
。这就是为什么编译器拒绝自动 eta-expand 方法 apply
的原因:类型不完全匹配。如果你显式地转换它,它就等同于 (d: DataMap) => Try.apply[DataMap](d)
,所以输入类型是 DataMap
,而不是 => DataMap
。
请注意,这会起作用:
val tryFunction: (=> DataMap) => Try[DataMap] = Try.apply[DataMap]
但它不能很好地与 compose
.
一起播放
我正在尝试组合这两个函数:
// some case class that just holds data
case class DataMap( ... )
val action(i: Int)(data: DataMap): DataMap = { ... }
val tryFunction: DataMap => Try[DataMap] = Try.apply[DataMap]
val actionFunction: DataMap => DataMap = action(2)
tryFunction compose actionFunction
然后我得到这些错误:
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `apply _` or `apply(_)` instead of `apply`.
val tryFunction = Try.apply[DataMap]
^
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `action _` or `action(_)` instead of `action`.
val actionFunction = action(1)
^
谁能解释为什么会出现这个错误,以及如何避免它?
这是因为 Try.apply
的别名参数。这在这里有效:
import util.Try
case class DataMap()
def action(i: Int)(data: DataMap): DataMap = ???
val tryFunction: DataMap => Try[DataMap] = Try.apply[DataMap](_)
val actionFunction: DataMap => DataMap = action(2)
tryFunction compose actionFunction
action(2)
不需要 eta 扩展,因为 DataMap => DataMap
类型归属强制编译器期望函数为 return 类型,因此 action(2)
是自动转换为action(2)(_)
。
Try.apply[DataMap]
必须显式转换 eta,因为 apply[A]
的输入类型是 => A
(按名称),而不仅仅是 A
。这就是为什么编译器拒绝自动 eta-expand 方法 apply
的原因:类型不完全匹配。如果你显式地转换它,它就等同于 (d: DataMap) => Try.apply[DataMap](d)
,所以输入类型是 DataMap
,而不是 => DataMap
。
请注意,这会起作用:
val tryFunction: (=> DataMap) => Try[DataMap] = Try.apply[DataMap]
但它不能很好地与 compose
.