tags:

views:

128

answers:

3

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

abstract class A { def f(x:Int) : Int }

class B extends A { f = identity }
+7  A: 

You can use a field of type function like this:

abstract class A { val f: (Int) => Int}

val identity = (x: Int) => x*x

class B extends A { override val f = identity }
deamon
And is there a difference between a method and a value like this? (P.S. identity is already define id Predef, and I don't want it to square the argument ;)
Michał Bendowski
Methods in Scala are *not* first-class entities. Values are. Functions are values (functions have to be first-class for just about any definition of a functional language). Methods are lifted to functions through partial application.
Randall Schulz
+3  A: 

Just to complement deamon's answer, here's one alternate example:

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

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, 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) }
Rex Kerr