What are all the uses of an underscore in Scala?

scala underscore type
scala default initializer
scala underscore lambda
_._2 in scala
scala dreaded underscore
scala underscore star
scala existential types
what does underscore means in scala

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. Explanatory examples are appreciated.

The ones I can think of are

Existential types
def foo(l: List[Option[_]]) = ...
Higher kinded type parameters
case class A[K[_],T](a: K[T])
Ignored variables
val _ = 5
Ignored parameters
List(1, 2, 3) foreach { _ => println("Hi") }
Ignored names of self types
trait MySeq { _: Seq[_] => }
Wildcard patterns
Some(5) match { case Some(_) => println("Yes") }
Wildcard patterns in interpolations
"abc" match { case s"a$_c" => }
Sequence wildcard in patterns
C(1, 2, 3) match { case C(vs @ _*) => vs.foreach(f(_)) }
Wildcard imports
import java.util._
Hiding imports
import java.util.{ArrayList => _, _}
Joining letters to operators
def bang_!(x: Int) = 5
Assignment operators
def foo_=(x: Int) { ... }
Placeholder syntax
List(1, 2, 3) map (_ + 2)
Method values
List(1, 2, 3) foreach println _
Converting call-by-name parameters to functions
def toFunction(callByName: => Int): () => Int = callByName _
Default initializer
var x: String = _   // unloved syntax may be eliminated

There may be others I have forgotten!


Example showing why foo(_) and foo _ are different:

This example comes from 0__:

trait PlaceholderExample {
  def process[A](f: A => Unit)

  val set: Set[_ => Unit]

  set.foreach(process _) // Error 
  set.foreach(process(_)) // No Error
}

In the first case, process _ represents a method; Scala takes the polymorphic method and attempts to make it monomorphic by filling in the type parameter, but realizes that there is no type that can be filled in for A that will give the type (_ => Unit) => ? (Existential _ is not a type).

In the second case, process(_) is a lambda; when writing a lambda with no explicit argument type, Scala infers the type from the argument that foreach expects, and _ => Unit is a type (whereas just plain _ isn't), so it can be substituted and inferred.

This may well be the trickiest gotcha in Scala I have ever encountered.

Note that this example compiles in 2.13. Ignore it like it was assigned to underscore.

What are all the uses of an underscore in Scala?, The ones I can think of are. Existential types. def foo(l: List[Option[_]]) = Higher kinded type parameters. case class A[K[_],T](a: K[T]). Ignored variables. val _ =  Use of underscore in Scala. Use of underscore: In programming languages, some special characters have found different uses. In this article, we will learn what are all the uses of an underscore in Scala? Underscore (_) character is reserved in Scala and has multiple usages in the programming language.

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.

Scala _ [underscore] magic · Anantha Kumaran, Initially i was annoyed by the use of too many symbols in Scala. _ // imports all the members of the object Fun but renames Foo to Bar import  The underscore in Scala has more than one use and it tends to be used a lot. That combination results in a lot of confusion — especially for folks who are new to the language. Instead of trying to cover every possible usage, I’d like to offer a few examples that build a basic intuition for two

An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.

Examples:

 def matchTest(x: Int): String = x match {
     case 1 => "one"
     case 2 => "two"
     case _ => "anything other than one and two"
 }

 expr match {
     case List(1,_,_) => " a list with three element and the first element is 1"
     case List(_*)  => " a list with zero or more elements "
     case Map[_,_] => " matches a map with any key type and any value type "
     case _ =>
 }

 List(1,2,3,4,5).foreach(print(_))
 // Doing the same without underscore: 
 List(1,2,3,4,5).foreach( a => print(a))

In Scala, _ acts similar to * in Java while importing packages.

// Imports all the classes in the package matching
import scala.util.matching._

// Imports all the members of the object Fun (static import in Java).
import com.test.Fun._

// Imports all the members of the object Fun but renames Foo to Bar
import com.test.Fun.{ Foo => Bar , _ }

// Imports all the members except Foo. To exclude a member rename it to _
import com.test.Fun.{ Foo => _ , _ }

In Scala, a getter and setter will be implicitly defined for all non-private vars in a object. The getter name is same as the variable name and _= is added for the setter name.

class Test {
    private var a = 0
    def age = a
    def age_=(n:Int) = {
            require(n>0)
            a = n
    }
}

Usage:

val t = new Test
t.age = 5
println(t.age)

If you try to assign a function to a new variable, the function will be invoked and the result will be assigned to the variable. This confusion occurs due to the optional braces for method invocation. We should use _ after the function name to assign it to another variable.

class Test {
    def fun = {
        // Some code
    }
    val funLike = fun _
}

Use of underscore in Scala, Use of underscore: In programming languages, some special characters have found different uses. In this article, we will learn What are all the  Scala has a lot of syntactic sugar. Despite the fact that most of times it pretty simply understandable, it occurs often that it increases the learning curve. One of symbols widely used in Scala and hard to understand at first contact is the underscore.

There is one usage I can see everyone here seems to have forgotten to list...

Rather than doing this:

List("foo", "bar", "baz").map(n => n.toUpperCase())

You could can simply do this:

List("foo", "bar", "baz").map(_.toUpperCase())

Underscore role in Scala on waitingforcode.com, One of symbols widely used in Scala and hard to understand at first contact all ignoring purposes we can also mention the use of underscore  In scala, a getter and setter will be implicitly defined for all non-private var in a object. The getter name is same as the variable name and _= is added for setter name. We can define our own getters and setters. This is looking similar to Ruby getters and setters. Ok lets see an example which uses the getter and setters.

Here are some more examples where _ is used:

val nums = List(1,2,3,4,5,6,7,8,9,10)

nums filter (_ % 2 == 0)

nums reduce (_ + _)

nums.exists(_ > 5)

nums.takeWhile(_ < 8)

In all above examples one underscore represents an element in the list (for reduce the first underscore represents the accumulator)

Underscores in Scala: The Basics - Matt Martin, underscore in Scala has more than one use and it tends to be used a if that underscore is supposed to represent an Int or a String or some  What are all the uses of an underscore in Scala? (6) An excellent explanation of the uses of the underscore is Scala _ [underscore] magic.

Underscores in Scala – Bonnie Eisenman, Doodling about the Scala underscore operator, feat. my awful this StackOverflow post: What are all the uses of underscore in Scala? Essential Scala is aimed at experienced developers who are encountering Scala for the first time. Put your existing skills to use mastering Scala’s combination of object-oriented and functional programming. The book teaches you Scala from the basics of its syntax to advanced problem solving techniques.

Why does Scala use the '_' operator for package import instead of , Because of this, Scala needed to use another symbol to indicate a wildcard import. @MikePatridge Almost definitely because Scala defines all of its operators as functions, In functional languages, the _ character is commonly used to say, "I don't care In Scala there are dozens of places where the underscore is used. A reference about every use cases of underscores in the Scala programming language Slideshare uses cookies to improve functionality and performance, and to provide you with relevant advertising. If you continue browsing the site, you agree to the use of cookies on this website.

How do I find what some symbol means or does? | FAQ, The last one, the underscore, deserve a special description, because it is widely used, and has different meanings depending on the context. Here's a sample:. Few local names are used (including parameters), and so there is no need to contrive long, descriptive names. This convention substantially improves the brevity of most Scala sources. This in turn improves readability, as most expressions fit in one line and the arguments to methods have descriptive type names.

Comments
  • I read this decent set of slides not long ago: Scala Dreaded Underscore
  • See also The Dreaded _ presentation on Slideshare
  • I think there are two or three that all fit under underscore usage in pattern matching, but +1 for joining letters to punctuation! :-)
  • val x: Any = _
  • @Owen I don't think println _ is a partially applied function. It is another example of placeholder syntax right? Meaning map(_ + 2) expands to something similar to map(x => x + 2) just as pritnln(_) expands to something similar to map(x => println(x))
  • @AndrewCassidy Actually println _ and println(_) are different. You can see this for example in that they handle existential and polymorphic types slightly differently. Will come up with an example in a bit.
  • @AndrewCassidy OK I have added an example.
  • May be you can add var i: Int = _ or the special case of pattern matching val (a, _) = (1, 2) or the special case of discarded val for (_ <- 1 to 10) doIt()
  • And def f: T; def f_=(t: T) combo for creating mutable f member.
  • Pattern matching is already covered, and _ on method names is cheating. But, well, ok. I just hope someone else updates the FAQ... :-)