美文网首页
cast & check

cast & check

作者: CentForever | 来源:发表于2021-10-10 20:47 被阅读0次
    import kotlin.contracts.InvocationKind
    import kotlin.contracts.contract
    
    inline fun <T: Any> T?.notNull(): T = checkNotNull(this)
    inline fun <T: Any> T?.notNull(lazyMessage: () -> String): T {
        contract { callsInPlace(lazyMessage, InvocationKind.AT_MOST_ONCE) }
        return checkNotNull(this, lazyMessage)
    }
    inline fun <T: Any> T?.notNull(message: String): T = checkNotNull(this) { message }
    
    inline fun <T: Any> T?.requireNotNull(): T = requireNotNull(this)
    inline fun <T: Any> T?.requireNotNull(lazyMessage: () -> String): T {
        contract { callsInPlace(lazyMessage, InvocationKind.AT_MOST_ONCE) }
        return requireNotNull(this, lazyMessage)
    }
    inline fun <T: Any> T?.requireNotNull(message: String): T = requireNotNull(this) { message }
    
    inline fun <T: Any> T.nullable(): T? = this
    
    fun <T> Class<T>.safeCast(obj: Any?) = if (isInstance(obj)) cast(obj) else null
    
    inline fun <T: Any> T?.orThrow(exception: () -> Throwable) = this ?: throw exception()
    inline fun <T: Any> T?.orThrow(exception: Throwable) = this ?: throw exception
    
    inline fun <T: Any, reified O> T?.cast() = this as O
    inline fun <T: Any, reified O> T?.castOrNull() = this as? O
    

    相关文章

      网友评论

          本文标题:cast & check

          本文链接:https://www.haomeiwen.com/subject/tubxcltx.html