Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to automatically convert class method to function taking explicit class argument in Scala?

Tags:

function

scala

The following is a manual process

case class A(x: Int) { def f(y: Int) = x * y }
val af: (A => Int => Int) = _.f

val a = A(4)
val r = af(a)(2)

Is there a conventient way to get a function like af? Something like A magic f, possibly without using reflection. Ability to import all public methods of a class via import A#magic._ is a bonus.

like image 785
ron Avatar asked Apr 06 '12 10:04

ron


2 Answers

This way is 10 symbols shorter:

val af = (_: A).f _
like image 104
senia Avatar answered Nov 15 '22 07:11

senia


You can create an instance of A and import the methods:

val a = A(4)
import a._

There is no other way of doing this, because x needs to hold a value. You could however create a singleton object instead af a class and change your method signatures accordingly:

object A {
  def f(x:Int)(y:Int) = x*y
}

import A._

As far as i know it is not possible to turn all methods of a class into curried (constructor)(method signature) functions.

like image 40
drexin Avatar answered Nov 15 '22 07:11

drexin