What are all the uses of an underscore in Scala?

后端 未结 7 1282
南笙
南笙 2020-11-21 07:24

I\'ve taken a look at the list of surveys taken on scala-lang.org and noticed a curious question: \"Can you name all the uses of “_”?\". Can you? If yes, please do so here.

7条回答
  •  半阙折子戏
    2020-11-21 07:28

    From (my entry) in the FAQ, which I certainly do not guarantee to be complete (I added two entries just two days ago):

    import scala._    // Wild card -- all of Scala is imported
    import scala.{ Predef => _, _ } // Exception, everything except Predef
    def f[M[_]]       // Higher kinded type parameter
    def f(m: M[_])    // Existential type
    _ + _             // Anonymous function placeholder parameter
    m _               // Eta expansion of method into method value
    m(_)              // Partial function application
    _ => 5            // Discarded parameter
    case _ =>         // Wild card pattern -- matches anything
    val (a, _) = (1, 2) // same thing
    for (_ <- 1 to 10)  // same thing
    f(xs: _*)         // Sequence xs is passed as multiple parameters to f(ys: T*)
    case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
    var i: Int = _    // Initialization to the default value
    def abc_<>!       // An underscore must separate alphanumerics from symbols on identifiers
    t._2              // Part of a method name, such as tuple getters
    1_000_000         // Numeric literal separator (Scala 2.13+)
    

    This is also part of this question.

提交回复
热议问题