Home > Back-end >  Convert non-nullable to nullable in Kotlin
Convert non-nullable to nullable in Kotlin

Time:09-06

I have an Entity class as below:


@Entity(name = "Person")
@Table(name = "person")
class Person(
    _firstName: String? = null,
    _lastName: String?,
    _address: String? = null)
) {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
    @GenericGenerator(name = "native", strategy = "native")
    var personId: Long? = null

    var firstName = _firstName
    var lastName = _lastName
    var address = _address
    
}

The repository is as :

@Repository
interface PersonRepository : JpaRepository<Person?, Long?> {
fun findByIdAndFirstName (personId: Long, firstName: String): Person?
}

In my service class I am doing a findById(personId) and getting an Optional<Person?> in return.

While writing the testcases I am running into an issue with the Optional.

@Test
    fun `test my changes`() {
        every { personRepository.findById(PERSON_ID) } answers { Optional.of(getPerson())}

    }
private fun getPerson(): Person {
        return Person(_firstName = "First Name", _lastName = "Last Name", _address = "Address")
    }

Since my getPerson() directly return the Person entity via a constructor the response is of type Person which is non-nullable. But personRepository.findById(PERSON_ID) expects a nullable type Optional<Person?>.

Getting this as compilation error in my test class:

Type mismatch.
Required:
Optional<Person?>!
Found:
Optional<Person>

How can I fix this issue ?

CodePudding user response:

You can cast it to nullable:

@Test
fun `test my changes`() {
    every { personRepository.findById(PERSON_ID) } answers {
        Optional.of(getPerson()) as Optional<Person?>
    }
}

However (as Sweeper said in the comment) the type Optional<Person?> doesn't make much sense, and it looks like your JpaRepository should be parameterized on non-nullables. If it was, then findById would return Optional<Person> and you wouldn't have this issue.

  • Related