【发布时间】:2017-07-13 21:53:25
【问题描述】:
我正在尝试实现一个公开具有 3 个覆盖的单个方法,以区分输入参数 - 每个 lambda 类型 - 根据以下示例:
//1:
def onAction(actionFn: =>Any) = ???
//2:
def onAction(actionFn: ()=>Any) = ???
//3:
def onAction(actionFn: (SomeEvent)=>Any) = ???
我正在寻找的是能够使用具有以下三种变体的代码:
//1: This would be used when defining some code inline
onAction { /* using the empty lambda block expression override */ }
//2: This would mainly be used when passing another function definition
onAction(()=> /* using the lambda expression override */ }
onAction(doMyCoolAction}
onAction(doMyOtherCoolAction}
def doMyCoolAction() : Unit = ???
def doMyOtherCoolAction() : Unit = ???
//3: Used when the "event type" is needed
onAction { e=> /* using the lambda expression with parameter */ }
这样的覆盖不能很好地协同工作,特别是 1.) 和 2.) 覆盖不能很好地协同工作...导致编译器在推断要使用哪个函数定义时出现问题。
有什么方法/解决方法可以让我完全使用这三个示例用法吗? (不添加额外的“杂乱”语法)
注意:我已经摆弄了定义单独的“ActionFn”类,并从三种不同的 lambda 类型进行隐式转换......但也没有运气:
def onAction(actionFn: ActionFn) = ???
class ActionFn {
//....
}
object ActionFn {
implicit def noArgLambdaBlockToActionFn(fn: =>Any) : ActionFn = ???
implicit def noArgLambdaToActionFn(fn: ()=>Any) : ActionFn = ???
implicit def argLambdaToActionFn(fn: (SomeEvent)=>Any) : ActionFn = ???
}
欢迎任何见解,谢谢:)
解决方案尝试: “目前为止的最佳解决方案”,给出了使用场景 3 的错误。):
//1:
def onAction(actionFn: =>Any) = ???
//2:
def onAction(actionFn: ()=>Any)(implicit d: DummyImplicit) = ???
//3:
def onAction(actionFn: (SomeEvent)=>Any)(implicit d: DummyImplicit) = ???
//3: Used when the "event type" is needed
//Error: "missing parameter type onAction({ e=>":
onAction { e=> /* using the lambda expression with parameter */ }
【问题讨论】:
-
: => Any扩展为() => Any。为什么需要这两个重载?选择一个。 -
好吧,如果我错了,请纠正我,但如果没有 1.) 定义,我不能使用用法示例 1.) - 类似我不能使用用法示例 2.)没有 2.) 定义?
标签: scala methods lambda overriding