Mikhail Erofeev Mikhail Erofeev - 6 months ago 30
Scala Question

How to write lambda for java.UnaryOperator<T> interface in Scala?

I've written this code in scala:

def push(x: T): Unit = ref.updateAndGet(new UnaryOperator[List[T]] {
override def apply(t: List[T]): List[T] = x :: t

And want to rewrite it in a more functional way, like

def push(x: T): Unit = ref.updateAndGet(t => x::t)

But it doesn't work. Is it possible to do such casting correctly?


In Scala 2.12 (RC 1 has already been released) this will be done automatically (i.e. ref.updateAndGet(t => x::t) will just work). In Scala 2.11 this already exists but under -Xexperimental compiler flag and the support is incomplete (I don't know the exact limitations).