简体   繁体   中英

arrow ensure doesn't make value non nullable after check

have a question about ensure function, somehow it doesn't make null safe after check in either block. What I am doing wrong, or is there a better way to ensure that value is not null except of using !! here is my code

 suspend fun checkCanConnectDirectChat(
    senderId: Int?,
    receiverId: Int?,
    chatRoomId: Int?
  ) = either {
    ensure(chatRoomId != null && receiverId != null) {
      BadRequestExceptionResponse(message = ErrorConstants.INVALID_PAYLOAD)
    }

    val isSenderInChat = isUserInChat(chatRoomId, senderId).bind()
    val isReceiverInChat = isUserInChat(chatRoomId, receiverId).bind()
    ensure(isSenderInChat && isReceiverInChat){
      BadRequestExceptionResponse(message = ErrorConstants.INVALID_PAYLOAD)
    }
  }

after the ensure I still see that they are nullable在此处输入图像描述

Unfortunately the compiler is not "clever enough" to know that if the check inside ensure talks about null-ness, then within the block that holds. The best solution is to use the *NotNull family of functions, some of them available at Arrow, some of them available in the standard library.

In this case you would use ensureNotNull , which smart-casts the value to be not nullable.

suspend fun checkCanConnectDirectChat(
    senderId: Int?,
    receiverId: Int?,
    chatRoomId: Int?
  ) = either {
    ensureNotNull(chatRoomId) {
     BadRequestExceptionResponse(message = ErrorConstants.INVALID_PAYLOAD)
    }

    ensureNotNull(receiverId) {
     BadRequestExceptionResponse(message = ErrorConstants.INVALID_PAYLOAD)
    }
    val isSenderInChat = isUserInChat(chatRoomId, senderId).bind()
    val isReceiverInChat = isUserInChat(chatRoomId, receiverId).bind()
    ensure(isSenderInChat && isReceiverInChat){
      BadRequestExceptionResponse(message = ErrorConstants.INVALID_PAYLOAD)
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM