Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

lambda

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?

like image 875
mishka Avatar asked Feb 07 '23 02:02

mishka


1 Answers

scala-java8-compat has java8 function converters

import scala.compat.java8.FunctionConverters._

def push(x: T): Unit = ref.updateAndGet(asJavaUnaryOperator(t => x::t))
like image 146
Lionel Port Avatar answered Feb 08 '23 16:02

Lionel Port