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