Reputation: 1539
Simple question one more time.
How can I specify in function/closure below that [more] should come from immutable type?
Other wise I am having this side effect as below!
Thanks
var more = 3
def increase[T: Numeric](x: T): T = implicitly[Numeric[T]].plus(x, more.asInstanceOf[T])
val inc = increase[Int] _
more = 10
println( inc(5) )
Upvotes: 2
Views: 79
Reputation: 37832
Not sure that's what you're looking for, but if you want to ensure the value used by the function doesn't change after a certain point, you can add it as a separate argument list, and partially-apply the function with its value:
var more = 3
def increase[T: Numeric](base: T)(x: T): T = implicitly[Numeric[T]].plus(x, base)
val inc = increase[Int](more) _
more = 10
println( inc(5) ) // prints 8, as expected
Upvotes: 5