Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>An excellent explanation of the uses of the underscore is <em><a href="http://ananthakumaran.in/2010/03/29/scala-underscore-magic.html" rel="noreferrer">Scala _ [underscore] magic</a></em>.</p> <p>Examples:</p> <pre><code> def matchTest(x: Int): String = x match { case 1 =&gt; "one" case 2 =&gt; "two" case _ =&gt; "anything other than one and two" } expr match { case List(1,_,_) =&gt; " a list with three element and the first element is 1" case List(_*) =&gt; " a list with zero or more elements " case Map[_,_] =&gt; " matches a map with any key type and any value type " case _ =&gt; } List(1,2,3,4,5).foreach(print(_)) // Doing the same without underscore: List(1,2,3,4,5).foreach( a =&gt; print(a)) </code></pre> <p>In Scala, <code>_</code> acts similar to <code>*</code> in Java while importing packages.</p> <pre><code>// 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 =&gt; Bar , _ } // Imports all the members except Foo. To exclude a member rename it to _ import com.test.Fun.{ Foo =&gt; _ , _ } </code></pre> <p>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 <code>_=</code> is added for the setter name.</p> <pre><code>class Test { private var a = 0 def age = a def age_=(n:Int) = { require(n&gt;0) a = n } } </code></pre> <p>Usage:</p> <pre><code>val t = new Test t.age = 5 println(t.age) </code></pre> <p>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.</p> <pre><code>class Test { def fun = { // Some code } val funLike = fun _ } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload