[英]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.作为前 Java 的人,我在 Kotlin 是全新的,并试图理解一些错误。
I am getting a record from db (Postgres) by using JpaRepository.我正在使用 JpaRepository 从 db (Postgres) 获取记录。 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 )
我想创建一个新记录,但新记录在其字段中只有 2 个不同的值,我想添加它(不更新前一个,而是添加一个新记录)
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 "我无法将新记录的 ID 设置为 null 以保存它,因为 ide 给出错误“ Null 不能是非空类型 Long 的值”
How can I create a new object by just updating some fields and making 'id' null to store it?如何通过仅更新一些字段并制作“id”null 来存储它来创建一个新的 object?
This is how you should define your class:这是你应该如何定义你的 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.因为我不知道 class 长什么样,我猜你一定有一个 class 或数据 class 长得像。
if you want declare a variable nullable you should use ?
如果你想声明一个可为空的变量,你应该使用
?
after its type.在它的类型之后。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.