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

前端 未结 3 1119
轮回少年
轮回少年 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: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() }
    :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.

提交回复
热议问题