Scala函数指针

Spa*_*key 5 scala

谷歌没有帮助我解决这个问题,我希望这并不意味着它不可能:

在我的班级中,我希望有一个定义了签名的方法,但是没有定义正文(method1)

将有许多定义的方法满足此签名(impl1,impl2,impl3)

当我初始化对象时,我将选择(基于某些标准)哪个方法实现impl1,impl2,impl3分配给函数指针method1

基本上我问我怎么能有一个函数指针,可以指向满足其签名的任何函数.

编辑:

所以,事实证明它实际上是非常直接的:

var method: Int => Int = (x => x+1)

method = (x => x-1)
method = (x => x*2)
etc...
Run Code Online (Sandbox Code Playgroud)

我之前的问题是我使用"val"或"def"来定义"方法"

不确定为什么不直接建议.许多人喜欢将函数作为参数添加到某个辅助类,然后使用特定实现初始化该类.也许有一些我缺少的东西.

编辑2:我现在意识到我没有得到我正在寻找的答案,因为我没有正确地说出我的问题,我应该说我想要"委托"行为,因为它在C#中.

Ida*_*rye 6

在Scala中,函数是对象,因此您可以:

class Foo(val func : Int => Int){
}
object Main{
    def main(args: Array[String]) {
        val foo1=new Foo(x => x + 1)
        val foo2=new Foo(x => x + 2)
        val foo3=new Foo(x => x + 3)
        println(foo1.func(10)) // Prints 11
        println(foo2.func(10)) // Prints 12
        println(foo3.func(10)) // Prints 13
    }
}
Run Code Online (Sandbox Code Playgroud)


blu*_*e10 1

你的意思是这样的:

class Whatever(selector: Int) {

  type Signature = Int => String

  private val implUsed = selector match {
    case 1 => impl1
    case _ => impl2
  }

  private val impl1: Signature = (i: Int) => i.toString
  private val impl2: Signature = (i: Int) => i.toString + "_suffix"

  def method: Signature = implUsed

}
Run Code Online (Sandbox Code Playgroud)

显然您也可以将impls 写为defs。也许基于继承的不同方法可能更好——您可能想澄清您想要实现的目标。虽然这种方法是对您的请求的字面解决方案,但传递函数本身会更惯用,就像 @Idan Arye 建议的那样。