samthebest samthebest - 3 days ago 5
Scala Question

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

According to this answer http://stackoverflow.com/a/8001065/1586965 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
val
is not implicit as it is utterly pointless?

Clarification

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

Answer

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.

Comments