Is there some reason to avoid return statements

后端 未结 3 1039
生来不讨喜
生来不讨喜 2021-02-04 01:14

Sometimes I see chunks of Scala code, with several nested levels of conditionals and matchings, that would be much clearer using an explicit return to exit from the function.

3条回答
  •  南旧
    南旧 (楼主)
    2021-02-04 02:12

    An explicit return breaks the control flow. For example if you have a statement like

    if(isAuth(user)) {
     return getProfile(user)
    }
    else {
     return None
    }
    

    the control structure (if) is not finished, which is the reason why I argue it is more confusing. For me this is analogous to a break statement. Additionally Scalas 'everything is a value' principle reduces the need for using explicit returns which leads to less people using a keyword which is only useful for def statements:

    // start 
    def someString:String = return "somestring"
    
    // def without return 
    def someString = "somestring"
    
    // after refactoring
    val someString = "somestring"    
    

    You see that the type annotation has to be added and when changing the def to a val it is required to remove the return.

提交回复
热议问题