【问题标题】:Why is `return` not allowed in Kotlin init block?为什么 Kotlin 初始化块中不允许“返回”?
【发布时间】:2017-09-15 16:57:46
【问题描述】:

如果我编译这个:

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

我收到一个错误:

错误:(18, 13) Kotlin: 'return' is not allowed here

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

【问题讨论】:

    标签: kotlin


    【解决方案1】:

    这是不允许的,因为对于几个 init { ... } 块可能会出现违反直觉的行为,这可能会导致细微的错误:

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

    如果答案为“否”,代码就会变得脆弱:在一个 init 块中添加 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 */
        }
    }
    

    【讨论】:

    • 使用多个初始化块,您可以使初始化逻辑接近成员声明。有时您可能还希望拆分单个 init 块以放置一个带有初始化器的属性,因为属性初始化器和 init 块的执行顺序与它们在代码中出现的顺序相同。
    • 这将是一个非常奇怪的用例,我看到多个init 调用并不直观(多次初始化对象......)。无论如何,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    相关资源
    最近更新 更多