Kotlin的DAO应该返回Optional还是null

Kotlin的DAO应该返回Optional还是null

本文介绍了Kotlin的DAO应该返回Optional还是null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Kotlin/JPA之前,我曾经这样写过DAO层:

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);
}

在主叫方,如果我想找到某人或通过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.

但是,由于Kotlin引入了null安全性,因此还有另一种惯用的方式(在Java中仍为dao):

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)
}

在客户端:

val user = userDao.findBySsnNullable(value)
      .takeIf{ it -> it != null}? : userDao.save(User(value))

两种方法都运作良好.但是我想知道哪个是首选的吗? Kotlin在API设计中依赖Java8的Optional是否对您有好处? Kotlin项目依赖(或通过Java8的Optional/Stream API进行相互通信)有什么弊端(因为Kotlin有自己的API)?

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可以编译为JavaScript(我还没有研究过).如果该项目依赖于Java的Optional/Stream,那么在编译为JS时会遇到问题吗?

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 ----

根据 Jetbrains

推荐答案

如果不需要,我不会使用Optional.它只会增加不必要的开销,因为在Kotlin中使用可空类型更易读和惯用.在Kotlin中使用Optional没有任何优势.

I wouldn't use Optional if you don't have to. It only adds unnecessary overhead as working with nullable types is more readable and more idiomatic in Kotlin. There's no advantage of using Optional in Kotlin.

这是另一个讨论: https://discuss.kotlinlang.org/t/java-api-design-for-kotlin-consumption-optional-or-null/2455

这篇关于Kotlin的DAO应该返回Optional还是null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 09:04