开发者

Implement a method using a function value in Scala

Is it poss开发者_如何学编程ible 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 }


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 }


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜