ayvango
ayvango

Reputation: 5977

What type does function has?

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 instance?

Upvotes: 4

Views: 129

Answers (2)

Channing Walton
Channing Walton

Reputation: 4007

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

inc _ $ 1

Upvotes: 3

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

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

Upvotes: 7

Related Questions