简体   繁体   中英

Converting this function to anonymous function

How do I create this function which returns true if a number is 5 to an anonymous function:

def yeah_five(p: Int): Boolean = p == 5

thanks?

Short notation for anonymous functions:

(p: Int) => (p == 5);

Long version:

new Function1[Int] {
  def apply(p: Int): Int = p == 5
}

You want a function that takes an Integer and returns a Boolean

(p: Int) => (p == 5);

Read through the tutorial on anonymous functions.

I guess the shortest way to write it would be like so:

val f: Int => Boolean = (_ == 5)

Of course, depending on the context you can loose the type annotation:

List(1, 2, 3, 5, 4, 5).filter(_ == 5)

=> List(5, 5)

As per @Senia's observation you can be even more succint with 5== wich transforms the == method of the object 5 to a function.

val g: Int => Boolean = 5==
List(1, 2, 3, 5, 4, 5).filter(g) => List(5, 5)

如果您要将已声明的方法转换为函数,请执行此操作

yeah_five _

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