Inject method using function value in Scala

Is it possible to implement a method using an object / function value? I would like to write something in the spirit:

abstract class A { def f(x:Int) : Int } class B extends A { f = identity } 
+4
source share
3 answers

And to complement deamon and Daniel , here's another:

 abstract class A { def f: (Int)=>Int } class B extends A { val f = identity _ } class C extends A { def f = identity _ } class D extends A { def f = (x:Int) => -x } 

If you are stuck with a normal def value, then the best you can do is

 abstract class Z { def f(x:Int):Int } class Y extends Z { def f(x:Int) = identity(x) } 
+1
source

You can use a field like type:

 abstract class A { val f: (Int) => Int} val identity = (x: Int) => x*x class B extends A { override val f = identity } 
+7
source

To complement deamon's answer , here is one alternative example:

 abstract class A { val f: (Int) => Int } class B extends A { val f: (Int) => Int = identity _ } 
+3
source

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


All Articles