What are all the uses of an underscore in Scala?

后端 未结 7 1157
南笙
南笙 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:48

    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 _
    }
    

提交回复
热议问题