Suppress “discarded non-Unit value” warning

风格不统一 提交于 2019-11-28 02:43:07

问题


I have added the scalac command line argument -Ywarn-value-discard to 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?


回答1:


You suppress these warning by explictly returning unit (that is ()). By example turn this:

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
}



回答2:


According to this answer, you can also use the syntax val _, i.e.

def method2(): Unit = {
  val _ = method1()
}

But there is some dispute over whether this or the answer by @Régis is the preferred style.




回答3:


Now you can suppress value-discard warning via type ascription to Unit in Scala 2.13.

This is an example:

def suppressValueDiscard(): Unit =
  "": Unit


来源:https://stackoverflow.com/questions/13415307/suppress-discarded-non-unit-value-warning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!