代码之家  ›  专栏  ›  技术社区  ›  four-eyes

转换数据类的值

  •  1
  • four-eyes  · 技术社区  · 5 月前

    假设我有一个这样的数据类

    data class PersonDTO(
        val id: Long?,
        val firstName: String,
        val lastName: String,
    )
    

    然后,我将其保存在该实体的数据库中

    @Entity
    @Table(name = "person")
    class Person(
        @Column(name = "first_name", nullable = true)
        var firstName: String? = null,
    
        @Column(name = "last_name", nullable = true)
        var lastName: String? = null,
    ) {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        val id: Long = 0
    }
    

    像这样

    personRepository.save(
        Person(
            firstName = personDto.firstName,
            lastName = personDto.lastName
        )
    )
    

    自从 firstName lastName nullable ,我想要 data class PersonDTO 按照以下方式操作:如果 名字 是的 length === 0 ,返回null 名字 (对于 姓氏 ).

    有办法做到这一点吗?

    2 回复  |  直到 5 月前
        1
  •  0
  •   Sweeper    5 月前

    我只需在数据类中添加新属性:

    data class PersonDTO(
        val id: Long?,
        val firstName: String,
        val lastName: String,
    ) {
        val nonEmptyFirstName: String?
            get() = firstName.takeUnless { it.isEmpty() }
        val nonEmptyLastName: String?
            get() = lastName.takeUnless { it.isEmpty() }
    }
    
    personRepository.save(
        Person(
            firstName = personDto.nonEmptyFirstName,
            lastName = personDto.nonEmptyLastName
        )
    )
    

    或者编写一个函数来转换为 Person 直接。

    fun PersonDTO.toPerson() = Person(
        firstName = firstName.takeUnless { it.isEmpty() },
        lastName = lastName.takeUnless { it.isEmpty() }
    )
    

    如果这不一定是一个数据类,你可以在不使用任何额外属性的情况下实现这一点。物业 firstName lastName 可以为null,但构造函数不接受 null .

    class PersonDTO(
        val id: Long?,
        firstName: String,
        lastName: String,
    ) {
        val firstName: String? = firstName
            get() = field?.takeUnless { it.isEmpty() }
        val lastName: String? = lastName
            get() = field?.takeUnless { it.isEmpty() }
    }
    
        2
  •  0
  •   Dr. Sa.M.    5 月前

    在我看来,你可以通过以下方式实现这一点

    第一次更改

    data class PersonDTO(
        val id: Long?,
        val firstName: String,
        val lastName: String,
    ) {
        // Use Function based calls
        fun getFirstName(): String? {
            return firstName.ifEmpty { null }
        }
    
        fun getLastName(): String? {
            return lastName.ifEmpty { null }
        }
    
        // Use calling variables directly
        val nullableFirstName: String? = firstName.ifEmpty { null }
        val nullableLastName: String? = lastName.ifEmpty { null }
    }
    

    第二次变更

    personRepository.save(
        Person(
            firstName = personDto.getFirstName(),
            lastName = personDto.getLastName()
        )
    )