2

I'm only a Kotlin newbie, but after I had lost some time because of it, I was wondering... why the following code does not result in compilation error since the second return in hello() or the print("ciao") in hello1 are clearly unreachable? (I'm confident that for other compilers, e.g. the Java compiler, this will be an error.)

fun main() {
   print(hello())
   print(hello1())
}

fun hello() : Boolean {
    return true // 1st return, this is always returned
    return false // 2nd return, unreachable
}

fun hello1() : Boolean {
    return true // 1st return, this is always returned
    print("ciao") // unreachable print
}

To be fair it gives a warning, but I'd like to have an error when such situations occur. Is there a way to make it an error?

1d0m3n30
  • 430
  • 6
  • 12
  • That isn't illegal, so it isn't an error. Your IDE should have emitted a warning though. If it didn't, check the warning settings. – Carcigenicate Aug 03 '19 at 15:51
  • You can make _all_ warnings into errors: https://stackoverflow.com/questions/34562200/how-do-i-make-the-kotlin-compiler-treat-warnings-as-errors. Not this one separately, AFAIK. – Alexey Romanov Aug 03 '19 at 16:21

1 Answers1

2

Unreachable statements don't result in compilation errors in Kotlin, because it's a language design decision. Java language designers decided for it to be an error, but not every language should agree with them.

Scala, another JVM language, takes same approach as Kotlin, and reports unreachable code as warning:

object Main extends App  {
  println(a() && b())

  def a(): Boolean = {
    return false
    return true
  }

  def b(): Boolean = {
    return true
    return false
  }
}

At some point, unreachable code was an error, but Kotlin team decided against it.

Now, as was already mentioned in the comments, you can turn all your warning into errors passing -Werror flag to Kotlin compiler. There's not specific flag for UNREACHABLE_CODE warning, though. You can try and request it, though, using YouTrack.

Alexey Soshin
  • 16,718
  • 2
  • 31
  • 40