2017-09-15 57 views
4

如果我編譯如下:爲什麼Kotlin init塊中不允許「return」?

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

我得到一個錯誤:

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

我不想與編譯器爭論,但我很好奇這個限制背後的動機。

回答

8

這是不允許的,因爲對於一些init { ... }塊可能反直覺的行爲,這可能會導致微妙的錯誤:

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

如果答案是「不」,代碼變得脆弱:在一個init塊中添加return會影響其他塊。

可能的解決方法,可以讓你完成一個init塊是使用具有拉姆達和a labeled return一些功能:

class C { 
    init { 
     run { 
      if (someCondition) [email protected] 
      /* do something otherwise */ 
     } 
    } 
} 

或者使用顯式定義secondary constructor

class C { 
    constructor() { 
     if (someCondition) return 
     /* do something otherwise */ 
    } 
} 
相關問題