samthebest samthebest - 1 year ago 81
Scala Question

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

According to this answer we can do this in Scala:

val _ = 5

Now I understand the point of ignored parameters in lambda expressions, but I cannot really imagine examples where I would ever want to declare a variable that by definition I cannot reference. The only example I can think of is being lazy about naming implicit values, e.g.

implicit val _: MyNumeric = ...
class A[T : MyNumeric] {

Is this the only use case? Am I missing something?

If it is the only use case, shouldn't the compiler/IDE give a warning/hint when the
is not implicit as it is utterly pointless?


By variable/value I mean a single one, not one that is part of an extraction declaration.

Answer Source

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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download