Scala avoid using null

前端 未结 5 1956
情深已故
情深已故 2021-01-18 04:07

I hava a project on github that is analysed by codacy . The analysis suggest to \"Avoid using null\" for the following line of code:

def doS         


        
5条回答
  •  离开以前
    2021-01-18 04:26

    the most idiomatic way would be to avoid the require (not sure but I have the idea it can thrown an exception - something Scala heavily recommends against)

    def doSomethingWithPath(path:Path): Option[stuff] = { // will return an option of the type you were returning previously.
         Option(path).map { notNullPath =>
           ...
         }
    }
    

    Now the possible null case will be returned to the caller, that can/will propagate the returned Option until the layer that knows how to handle it properly.

    Note: it is possible that the best place to handle the null case is inside you function. In that case you should do something like

    Option(path).map { notNullPath =>
        ...
    }.getOrElse(/* take care of null case */)
    

    If you do want to keep the require, then the answer by jwvh would be my choice also

提交回复
热议问题