我想编写一个简单的方法,将函数作为参数然后执行它.
def exec(f: (a:Int, b:Int) => Boolean): Boolean = f(a,b)
Run Code Online (Sandbox Code Playgroud)
我不确定上面有什么问题,但我收到错误:
<console>:1: error: ')' expected but ':' found.
Run Code Online (Sandbox Code Playgroud)
def exec(f: (a:Int, b:Int) => Boolean): Boolean = f(a,b)
^ ^
| |
// These are supposed to be types, but a: Int and b: Int aren't types,
// they are identifiers with type ascriptions.
Run Code Online (Sandbox Code Playgroud)
它看起来应该更像:
def exec(f: (Int, Int) => Boolean): Boolean = f(a, b)
Run Code Online (Sandbox Code Playgroud)
现在f是一个功能(Int, Int) => Boolean.但这不会编译,因为a并b没有定义.
您需要传入它们,或将它们修复为值.
def exec(a: Int, b: Int)(f: (Int, Int) => Boolean): Boolean = f(a, b)
scala> exec(2, 3)(_ > _)
res1: Boolean = false
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |