再问一次简单问题。
如何在下面的函数/闭包中指定 [more] 应该来自不可变类型?
否则我会产生如下副作用!
谢谢
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) )
最佳答案
不确定这就是您要寻找的,但是如果您想确保函数使用的值在某个点之后不会更改,您可以将其添加为单独的参数列表,并部分应用该函数及其值(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
关于scala:在闭包中强制执行不可变类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36402960/