What is a function literal in Scala?

后端 未结 3 773
故里飘歌
故里飘歌 2020-12-01 00:25

What is a function literal in Scala and when should I use them?

3条回答
  •  时光说笑
    2020-12-01 01:08

    It might be useful to compare function literals to other kinds of literals in Scala. Literals are notational sugar for representing values of some types the language considers particularly important. Scala has integer literals, character literals, string literals, etc. Scala treats functions as first class values representable in source code by function literals. These function values inhabit a special function type. For example,

    • 5 is an integer literal representing a value in Int type
    • 'a' is a character literal representing a value in Char type
    • (x: Int) => x + 2 is a function literal representing a value in Int => Int function type

    Literals are often used as anonymous values, that is, without bounding them to a named variable first. This helps make the program more concise and is appropriate when the literal is not meant to be reusable. For example:

    List(1,2,3).filter((x: Int) => x > 2)
    

    vs.

    val one: Int = 1
    val two: Int = 2
    val three: Int = 3
    val greaterThan2: (Int => Int) = (x: Int) => x > two
    List(one,two,three).filter(greaterThan2)
    

提交回复
热议问题