简体   繁体   中英

Perform anonymous function on an object

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM