代码之家  ›  专栏  ›  技术社区  ›  Martin Drozdik rlbond

为什么在Kotlin init块中不允许“return”?

  •  35
  • Martin Drozdik rlbond  · 技术社区  · 7 年前

    如果我编译这个:

    class CsvFile(pathToFile : String)
    {
        init 
        {
            if (!File(pathToFile).exists())
                return
            // Do something useful here
        }
    }
    

    我收到一个错误:

    错误:(18,13)Kotlin:此处不允许“return”

    我不想与编译器争论,但我很好奇这个限制背后的动机。

    1 回复  |  直到 7 年前
        1
  •  39
  •   hotkey    7 年前

    这是不允许的,因为在几个方面可能有违反直觉的行为 init { ... } 块,这可能会导致微妙的错误:

    class C {
        init { 
            if (someCondition) return
        }
        init {
            // should this block run if the previous one returned?
        }
    }
    

    如果答案是“否”,代码就会变得脆弱:添加一个 return 在一个 init 块会影响其他块。

    初始化 块是使用lambda和 a labeled return :

    class C {
        init {
            run {
                if (someCondition) return@run
                /* do something otherwise */
            }
        }
    }
    

    或者使用明确定义的 secondary constructor :

    class C {
        constructor() { 
            if (someCondition) return 
            /* do something otherwise */
        }
    }