blue
10/11/2021, 10:30 PMval record = (repository.findById(id) ?: (<http://log.info|log.info>("log message here") return))
Paul Griffith
10/11/2021, 10:32 PMrun
for this;
val record = repository.findById(id) ?: run {
<http://log.info|log.info>("log message here")
return
}
Richard Gomez
10/11/2021, 11:08 PMephemient
10/11/2021, 11:35 PMval record = repository.findById(id)
if (id == null) {
<http://log.info|log.info>("log message here")
return
}
will work equivalently, as the val
is smart-cast to non-null after the conditionalephemient
10/11/2021, 11:47 PM<http://log.info|log.info>
returns Unit
you can get away with
val record = repository.findById("id") ?: return <http://log.info|log.info>("log message here")
but I do not recommend it; stylistically, I would tend to avoid treating Unit
as a value where unnecessaryMichael Böiers
10/12/2021, 5:51 AMKlitos Kyriacou
10/12/2021, 8:45 AMStephan Schroeder
10/12/2021, 9:13 AMUnit
😉
Assuming your method returns Record
(which is what your error message seems to tell us), this leads to the question: So what do you want to return in case repository.findById(..)
returns null
?
I see three possibilities:
• return a nullable Record
• throw an exception
val record = repository.findById(id) ?: run {
<http://log.info|log.info>("log message here")
throw NoSuchElementException("no record found with id $id")
}
• return a default
val defaultRecord = ... //should be outside of the method, so you always return the same instance
...
val record = repository.findById(id) ?: run {
<http://log.info|log.info>("log message here")
return defaultRecord
}
of course you can only return a default value if a logical/useful default value exists. otherwise return null. null in Kotlin is more benevolent than in Java, since it can't surprise you, so use it where appropriate.Michael Böiers
10/12/2021, 9:18 AM