如何重载scala函数apply方法
正确的语法是将 withLoaner 参数移动到重载的 apply 方法?我尝试了以下几个版本均未成功。另外,非常感谢对我的错误概念的任何见解。
def withLoaner = new {
def apply(n:Int, op: Int => String):String = (1 to n).map(op).mkString("\n")
def apply(n:Int, op: () => String):String = apply{n, i:Int => op()} // no compile
def apply(op: () => String):String = apply{1, i:Int => op()} // no compile
}
As a follow on to: scala loan pattern, optional function param
What would the proper syntax be to move the withLoaner param to overloaded apply methods? I've tried several versions of the following unsuccessfully. Also, any insights into my error conceptually very appreciated.
def withLoaner = new {
def apply(n:Int, op: Int => String):String = (1 to n).map(op).mkString("\n")
def apply(n:Int, op: () => String):String = apply{n, i:Int => op()} // no compile
def apply(op: () => String):String = apply{1, i:Int => op()} // no compile
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
传递多个参数时,必须使用括号将它们括起来。使用 {} 仅适用于单个参数。
此外,在使用函数文字时,如果指定类型,则必须将所有函数参数放在括号内。
所以,
When passing multiple parameters, you must use parenthesis around them. Using {} only works for single parameters.
Also, when using function literals, if you specify type, you have to put all of the functions parameters inside parenthesis.
So,
2 个小变化:
在调用
apply
时使用(
而不是{
:apply(.......)
在隐式函数的参数周围使用
(
:apply(1, (i:Int) => op())
2 little changes:
Use
(
instead of{
when callingapply
:apply(.......)
Use
(
around the arg to an implicit function:apply(1, (i:Int) => op())