簡體   English   中英

為什么無法訪問的語句方法不會導致編譯錯誤?

[英]Why do unreachable statements method not result in a compilation error?

我只是一個 Kotlin 新手,但是在我因為它而失去了一些時間之后,我想知道......為什么自從hello()或 print("ciao" ) 在hello1中顯然無法訪問? (我相信對於其他編譯器,例如 Java 編譯器,這將是一個錯誤。)

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
}

公平地說,它會發出警告,但我希望在發生這種情況時出現錯誤。 有沒有辦法讓它出錯?

無法訪問的語句不會導致 Kotlin 中的編譯錯誤,因為它是一種語言設計決策 Java 語言設計者認為這是一個錯誤,但並非每種語言都應該同意他們

Scala 是另一種 JVM 語言,它采用與 Kotlin 相同的方法,並將無法訪問的代碼報告為警告:

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

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

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

在某些時候,無法訪問的代碼是一個錯誤,但 Kotlin 團隊決定反對它。

現在,正如評論中已經提到的,您可以將所有警告轉換為錯誤,將-Werror標志傳遞給 Kotlin 編譯器。 但是,沒有針對UNREACHABLE_CODE警告的特定標志。 不過,您可以嘗試使用YouTrack請求它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM