问题描述
根据这个答案 https://stackoverflow.com/a/8001065/1586965 我们可以在 Scala 中做到这一点:
According to this answer https://stackoverflow.com/a/8001065/1586965 we can do this in Scala:
val _ = 5
现在我理解了 lambda 表达式中忽略参数的意义,但我无法想象我想要声明一个根据定义我无法引用的变量的例子.我能想到的唯一例子是懒惰地命名隐式值,例如
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?
如果这是唯一的用例,当 val
是 not 隐含的,因为它完全没有意义时,编译器/IDE 不应该给出警告/提示吗?
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?
澄清
变量/值是指单个变量/值,而不是作为提取声明一部分的变量/值.
By variable/value I mean a single one, not one that is part of an extraction declaration.
推荐答案
它使用一个值.
$ 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>
为了验证,它在-Ywarn-unused
下也没有警告.
To verify, it also doesn't warn under -Ywarn-unused
.
这篇关于Scala 中忽略变量语法的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!