According to this answer https://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.
_1 is a method name. Specifically tuples have a method named _1 , which returns the first element of the tuple.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
=> is syntactic sugar for creating instances of functions. Recall that every function in scala is an instance of a class. For example, the type Int => String , is equivalent to the type Function1[Int,String] i.e. a function that takes an argument of type Int and returns a String .
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() }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With