What is the use cases of Ignored Variable syntax in Scala?

前端 未结 3 1108
轮回少年
轮回少年 2020-12-15 10:56

According to this answer https://stackoverflow.com/a/8001065/1586965 we can do this in Scala:

val _ = 5

Now I understand the point of ignor

相关标签:
3条回答
  • 2020-12-15 11:24

    The other use case (that I can think of) is related to extraction (and is called out under "Wildcard patterns" in the linked answer):

    val getCartesianPoint = () => (1, 2, 3)
    // We don't care about the z axis, so we assign it to _
    val (x, y, _) = getCartesianPoint()
    
    val regex = "(.*?)|(.*?)|?.*".r
    // Really, any unapply or unapplySeq example will do
    val regex(_, secondValue) = "some|delimited|value|set"
    
    0 讨论(0)
  • 2020-12-15 11:29

    I don't think that this is a feature at all. In any case, it is not an "ignored variable". By which I mean that if val _ = 5 really introduced an unnamed value, then you could declare as many as you want in the same single scope. Not so:

    scala> object Test {
         |   val _ = 5
         |   val _ = 7
         | }
    <console>:9: error: _ is already defined as value _
             val _ = 7
             ^
    

    From the error message it seems clear that what really happens is that the value is actually named _ (which I'd call a quirk of the compiler that should be fixed). We can verify this:

    scala> object Test {
         |   val _ = 5
         |   def test() { println( `_` ) } // This compiles fine
         | }
    defined object Test
    
    scala> Test.test()
    5
    

    As for the possible use of preventing a value discarding warning (as shown in som-snytt's answer), I'much prefer to simply return an explicit Unit. This looks less convoluted and is even shorter:

    def g(): Unit = { f(); () }
    

    as opposed to:

    def g(): Unit = { val _ = f() }    
    
    0 讨论(0)
  • 2020-12-15 11:48

    It uses a value.

    $ scala -Ywarn-value-discard
    Welcome to Scala version 2.11.2 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_11).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> def f() = { println("I ran.") ; 42 }
    f: ()Int
    
    scala> def g(): Unit = { f() }
    <console>:8: warning: discarded non-Unit value
           def g(): Unit = { f() }
                              ^
    g: ()Unit
    
    scala> def g(): Unit = { val _ = f() }
    g: ()Unit
    
    scala> g
    I ran.
    
    scala> 
    

    To verify, it also doesn't warn under -Ywarn-unused.

    0 讨论(0)
提交回复
热议问题