nullable => Optional
If you're writing code in Kotlin, you'll need to convert it to Java Optional.
In such cases, use ʻOptional.ofNullable to convert to ʻOptional
.
You can also use ʻOptional.of` if it is not nullable.
class SecurityAuditorAware: AuditorAware<Long> {
override fun getCurrentAuditor(): Optional<Long> {
val authentication = SecurityContextHolder.getContext().authentication
if (authentication == null || !authentication.isAuthenticated) {
return Optional.ofNullable(null)
}
return Optional.ofNullable((authentication.principal as UserDetail?)?.user?.id)
}
}
From Java's point of view, Kotlin's nullable looks the same as it isn't, so ʻOptional <Long?>, ʻOptional <Long>
, ʻOptional , And ʻOptional <Long?>?
Is the same. You can use those four patterns for the return type of getCurrentAuditor ()
in the sample.
Optional => nullable / not-nullable
Using findById
in a Spring 5 repository will return ʻOptional . In such cases, you may want to extract the contents from ʻOptional
to pass a value to Kotlin.
optionalValue.get() => not-nullable
optionalValue.orElse(null) => nullable
There are many other methods available for values of type ʻOptional`.
It was described in detail in the next article. https://qiita.com/tasogarei/items/18488e450f080a7f87f3
Recommended Posts