ARK91
ARK91

Reputation: 373

Case Class with higher order function in Parameter

Suppose Case Class which takes higher order function in parameters. eg.

case class CC(a: String = "1",b: Int => Int,c : Int = 0,d: Boolean = false)
val v = 3
val rc = CC ("1",v => v+v,0,true) //rc: CC = CC(1,A$A161$A$A161$$Lambda$1856/1364270469@44fc4b1b,0,true)

Why scala gives the class rather associate Int value to "b"?

Upvotes: 0

Views: 202

Answers (2)

Leo C
Leo C

Reputation: 22439

As others have pointed out, v in your function defintion is unrelated to the assigned val v. Maybe the following example would help clarify:

case class CC(a: String = "1", b: Int => Int, c : Int = 0, d: Boolean = false)
val v = 3

// `v` below is unrelated to the assigned val `v`
val rc = CC ("1", v => v + v, 0, true)
rc.b(1)
// res1: Int = 2

// `v` below is the assigned val `v`
val rc = CC ("1", x => x + v, 0, true)
rc.b(1)
// res2: Int = 4

Upvotes: 1

thesamet
thesamet

Reputation: 6582

It's worth noting that the second line in your code (val v = 3) is not used. The second parameter to your case class is defined in the first line of your code to be a function that takes an Int and gives back an Int. In the third line, you instantiate an instance of CC by correctly passing such a function: v => v + v as the parameter b.

When the REPL displays an instance of CC to you it shows you a class that corresponds to the anonymous function you passed as b.

Upvotes: 1

Related Questions