Scala function pointer

Google did not help me with this question, I hope this does not mean that this is impossible:

In my class I want to have a method that has a signature but the body is not defined (method1)

There will be many specific methods that satisfy this signature (impl1, impl2, impl3)

When I initialize the object, I will then select (based on some criteria) which implementation of the impl1, impl2, impl3 method to assign to the function pointer method1

Basically, I ask how I can have a pointer to a function that can point to any function that satisfies its signature.

EDIT:

So it turns out that this is really very straightforward:

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

method = (x => x-1)
method = (x => x*2)
etc...

My problem before was that I used "val" or "def" to define a "method"

, . , . , -, .

2: , , , , , "" , #.

+4
4

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
    }
}
+6

:

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

}

impl def s. , , , , , . , , @ .

+1

And here is a not very elegant approach with inheritance:

abstract class Foo() {
  def say(): String

  protected def bark = "Woof!"
  protected def quack = "Quack!"
}

val dog = new Foo() {
  def say() = bark
}

dog.say
// res2: String = Woof!
+1
source

In this case, I would not use the method at all. Just enter a field that you can initialize for the specific function you want. Sort of:

class Foo(val method1: Int => Int)

val doubler     = new Foo(2*)
val incrementer = new Foo(1+)
val absolute    = new Foo(_.abs)
val parity      = new Foo(_ % 2)
val doesNothing = new Foo(identity)

doubler.method1(-3)     // => -6
incrementer.method1(-3) // => -2
absolute.method1(-3)    // =>  3
parity.method1(-3)      // => -1
doesNothing.method1(-3) // => -3
0
source

Source: https://habr.com/ru/post/1538578/


All Articles