Prior to Kotlin/JPA , I used to write my DAO layer like this :
public interface UserDao extends JpaRepository<User,Long> {
Optional<User> findBySsn(String ssn);
}
And in the caller side , if I want to find someone or create user by SSN , I can write this:
val user = userDao.findBySsn(value).orElseGet {
userDao.save(value)
}
It works well and looks fluent.
But since Kotlin introduces null-safety , there is another idiomatic way (dao still in Java ):
public interface UserDao extends JpaRepository<User,Long> {
Optional<User> findBySsn(String ssn);
@Query("select u from User u where u.ssn = :ssn")
@Nullable User findBySsnNullable(@Param("ssn") String ssn)
}
And in the client side :
val user = userDao.findBySsnNullable(value)
.takeIf{ it -> it != null}? : userDao.save(User(value))
Both ways work good. But I wonder which is preferred ? Is it good for Kotlin to dependent on Java8's Optional in API design ? What's the cons for a Kotlin project to depend on (or intercommunicate via) Java8's Optional/Stream API (since Kotlin has its own) ?
Kotlin can compile to JavaScript (I haven't studied that). If the project is depend on Java's Optional/Stream , will it have problem compiling to JS?
---- updated ----
According to Jetbrains
No, common code can only depend on other common libraries. Kotlin has no support for translating Java bytecode into JS.