Suppress "Discarded Non-Unit Value" Warning

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?

3 Answers

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.

4

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

This is an example:

def suppressValueDiscard(): Unit =
  "": Unit
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest