4

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 }

3 Answers 3

7

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 }
Sign up to request clarification or add additional context in comments.

2 Comments

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 ;)
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.
3

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 _ }

Comments

1

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) }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.