Home > Mobile >  Perform anonymous function on an object
Perform anonymous function on an object

Time:01-19

This is probably very simple but I'm trying to perform an anonymous function on a list object (not the elements of a list). For example, is it possible to write the following as a single line?

val a = List(1,2,3)
val b = a :  a.last

I'm just trying to make some code a bit more concise/ avoid meaningless val names

I have tried searching online documentation, but without knowing the technical terms for what I'm trying to achieve, I haven't found anything

CodePudding user response:

Yes, it is possible to define an anonymous function and invoke it immediately:

val b = ((a: List[Int]) => a :  a.last)(List(1, 2, 3))
// val b: List[Int] = List(1, 2, 3, 3)

However, this still requires the definition of a meaningless parameter name a, and is arguably less concise and harder to understand than the original code.

As Luis Miguel Mejía Suárez noted in the comments, the pipe method is an alternative option that allows the type of the a parameter to be inferred:

import scala.util.chaining._

val b = List(1, 2, 3).pipe(a => a :  a.last)

If the goal is to avoid polluting the local variable namespace, another option is a block expression:

val b = {
  val a = List(1,2,3)
  a :  a.last
}
  • Related