开发者

What type does function has?

开发者 https://www.devze.com 2023-03-26 21:56 出处:网络
I missed haskell\'s convenient operator $ so I have decided to introduce one. class Applayable[-R,T] (val host : Function[R,T]) {

I missed haskell's convenient operator $ so I have decided to introduce one.

class Applayable[-R,T] (val host : Function[R,T]) {
  def $: R=>T = host.apply
}
implicit def mkApplayable[R,T] (k : Function[R,T]) : Applayable[R,T] = new Applayable(k)

It has perfrectly worked for

val inc : Int => Int = _ + 1
inc $ 1

but failed for

def inc(x:Int) : Int = x+1
inc $ 1

What type should I specify for implicit cast to convert def definition to an Applayable in开发者_C百科stance?


You cannot specify a type to do what you want: methods are not functions. You can transform a method into a (possibly partially applied) function by appending the magical underscore after it, like this:

def inc(x:Int) : Int = x+1
(inc _) $ 1


you need to treat the inc method as a function by appending '_'. This works:

inc _ $ 1
0

精彩评论

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