Suppress “discarded non-Unit value” warning

佐手、 提交于 2019-11-29 09:03:09

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

def method1() = {
   println("Hello")
   "Bye"
}
def method2() {
  method1() // Returns "Bye", whihc is implicitly discarded
}

into:

def method1() = {
   println("Hello")
   "Bye"
}
def method2() {
  method1()
  () // Explicitly return unit
}
Todd Owen

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.

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

This is a exmaple:

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