简单的问题再一次.
我如何在函数/闭包中指定[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) )
Run Code Online (Sandbox Code Playgroud)
不确定这是你要找的东西,但是如果你想确保函数使用的值在某一点之后不会改变,你可以将它作为单独的参数列表添加,并部分地应用函数及其值:
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
Run Code Online (Sandbox Code Playgroud)