Issue
I'm looking for the best way in Kotlin (/ Spring Boot) to save in ObjectA ObjectB (and other values) in my service:
fun create(objectARequest: ObjectARequest): ObjectA {
val foundObjectB = objectBRepository.findById(objectARequest.objectBId)
val objectA = ObjectA(
id = UUID.randomUUID(),
...
objectB = foundObjectB.get()
)
return objectARepository.save(objectA)
}
My question is related to this line objectB = foundObjectB.get()
:
This is the Java way (implementation from java.utils), so it this the best approach or should I simply go with objectB = foundObjectB
? What is the best practice in Kotlin here?
Solution
Optional is a Java workaround to deal with null. Kotlin has a much better way, by explicitly defining nullability. Having said that, I would suggest you replacing Optional with null or the object itself if present. You can do this with “orElse(null)”. By doing so you either have null or the object. Now you are in the Kotlin realm again with all its benefits.
val foundObjectB : ObjectB? = objectBRepository.findById(objectARequest.objectBId).orElse(null)
Additionally, keep in mind that “get()” on an optional would throw NoSuchElementException if no object is present.
Answered By - João Dias
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.