Why can't I throw an exception while using the ternary operator

前端 未结 4 1085
南旧
南旧 2021-02-13 03:49

This doesn\'t compile and gives the following error : Illegal start of expression. Why?

public static AppConfig getInstance() {
        return mConf         


        
4条回答
  •  南方客
    南方客 (楼主)
    2021-02-13 04:21

    In case it's helpful to someone, here is an answer using java 8+ Optional:

    public static AppConfig getInstance() {
        return Optional.ofNullable(mConfig).orElseThrow(() -> new RuntimeException("error"));
    }
    

提交回复
热议问题