简体   繁体   中英

How to create object in Kotlin without getting "Null can not be a value of a non-null type Long"?

I am totally new in Kotlin as a former Java guy and try to understand some errors.

I am getting a record from db (Postgres) by using JpaRepository. I want to create a new record but the new record will only have 2 different value in its fields and I want to add it ( not updating the previous one, instead adding new one )

val otp = notificationRepository.findById(id).get()
        val newOtp = otp
        newOtp.delivery = newOtp.delivery.plusMinutes(OTP_RESEND_TIME_IN_MINUTES);
        newOtp.status = NotifyStatus.PENDING
        newOtp.id = null // HERE I AM GETTING ERROR
        //save logic here

I cannot set id of the new record to null to save it because the ide giving error " Null can not be a value of a non-null type Long "

How can I create a new object by just updating some fields and making 'id' null to store it?

This is how you should define your class:

class Notification(
    val id: Long?,
    val status: NotifyStatus,
    val delivery: DateTime
)

As i did not know what the class look like, i guess you must have a class or data class look like it.

if you want declare a variable nullable you should use ? after its type.

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