scala 禁止“丢弃的非单位值”警告
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13415307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Suppress "discarded non-Unit value" warning
提问by Robin Green
I have added the scalac command line argument -Ywarn-value-discardto my build because this would have caught a subtle bug that I just found in my code. However, I now get some warnings for "discarded non-Unit value" that are about intentional discards, not bugs. How do I suppress those warnings?
我已将 scalac 命令行参数添加-Ywarn-value-discard到我的构建中,因为这会捕获我刚刚在我的代码中发现的一个微妙的错误。但是,我现在收到一些关于“丢弃的非单位值”的警告,这些警告是关于故意丢弃的,而不是错误。我如何抑制这些警告?
回答by Régis Jean-Gilles
You suppress these warning by explictly returning unit (that is ()).
By example turn this:
您可以通过显式返回 unit(即())来抑制这些警告。举个例子:
def method1() = {
println("Hello")
"Bye"
}
def method2() {
method1() // Returns "Bye", which is implicitly discarded
}
into:
进入:
def method1() = {
println("Hello")
"Bye"
}
def method2() {
method1()
() // Explicitly return unit
}
回答by Todd Owen
According to this answer, you can also use the syntax val _, i.e.
根据这个答案,您还可以使用语法val _,即
def method2(): Unit = {
val _ = method1()
}
But there is some dispute over whether this or the answer by @Régis is the preferred style.
但是对于这个或@Régis 的答案是否是首选风格存在一些争议。
回答by floating cat
Now you can suppress value-discard warning via type ascription to Unitin Scala 2.13.
现在,你可以通过抑制类型归属价值丢弃警告,Unit在斯卡拉2.13。
This is an example:
这是一个例子:
def suppressValueDiscard(): Unit =
"": Unit

