Access a member of a class from a first class function

I have a case class that accepts a list of functions:

case class A(q:Double, r:Double, s:Double, l:List[(Double)=>Double])

I have over 20 functions. Some of these functions have their own settings, and some of them also use values q, rand sfrom the class of case. Two examples:

def f1(w:Double) = (d:Double) => math.sin(d) * w
def f2(w:Double, q:Double) = (d:Double) => d * q * w

The problem is that then I need to reference q, rand stwice when instantiating the case class:

A(0.5, 1.0, 2.0, List(f1(3.0), f2(4.0, 0.5))) //0.5 is referenced twice

I would like to be able to instantiate the class as follows:

A(0.5, 1.0, 2.0, List(f1(3.0), f2(4.0))) //f2 already knows about q!

What is the best technique for this? Can I define my functions in an attribute that extends the case class?

EDIT: A real-world application consists of 7 members, not 3. Only a small number of functions need access to members. Most functions do not care about them.

+3
3

val:

val a = 0.5
A(a, 1.0, 2.0, List(f1(3.0), f2(4.0, a)))

f2 A this, , A A. , . , f2, A.

, . , , ​​ A.

+3

q f2 q case class, :

trait TraitA {                                                                                       
  def q:Double                                                                                       
  def r:Double                                                                                       
  def s:Double                                                                                       

  def f1(w:Double) = (d:Double) => math.sin(d) * w                                                   
  def f2(w:Double) = (d:Double) => d * q * w                                                         
}                                                                                                    

case class A(q:Double, r:Double, s:Double, l:List[(Double)=>Double]=Nil) extends TraitA              

val a=new A(0.5, 1.0, 2.0){override val l= List(f1(3.0), f2(4.0))}                                   
+5

One simple idea would be to change the function to take a list of functions that occupy 3 doubles (q, r and s) and return the function from double to double. Thus, those functions that need some kind of value can use them, while others simply ignore them all.

+1
source

Source: https://habr.com/ru/post/1746055/


All Articles