Handling nullable return types in Kotlin data class initialization with known non-null values

88 Views Asked by At

I'm encountering an issue while initializing a Kotlin data class, specifically when dealing with nullable and non-nullable properties. I have two data classes, StartObject and EndObject, and a generic data class DataSet.

Below is the simplified code of my issue.

data class EndObject(
  val neverNullDataSet: DataSet<String>,
  val nullableDataSet: DataSet<String>?
) {
  companion object {
    fun from(startObject: StartObject): EndObject{
      return EndObject (
        neverNullDataSet = createDataSet(startObject.neverNullValue),
//above results in error because createDataSet returns DataSet<String>?, even though it can't be null
        nullableDataSet = createDataSet(startObject.nullableValue) 
//above is ok, as expected
       )
    }
    fun createDataSet(value: String?): DataSet<String>? {
       return if (value == null) null
       else DataSet(value)
    }
  }
}

data class StartObject(
  val neverNullValue: String,
  val nullableValue: String?
)

data class DataSet<String>( 
  val importantValue: String // Will never be null since it won't be created if importantValue is missing
)

The issue arises when calling the createDataSet function within the companion object constructor. The createDataSet function returns a nullable DataSet?, but the neverNullDataSet property in EndObject expects a non-nullable DataSet. This results in a compilation error.

While I understand that the createDataSet function may return null in certain cases, I know that it won't return null when called with startObject.neverNullValue. In other words, the returned value will always be non-null, even though the return type allows nullability.

Is there a way to handle this situation where the return type of createDataSet is nullable, but it is known that it won't be null in certain scenarios? I want to avoid having to make the neverNullDataSet property nullable in the EndObject class. I'm aware of the null safety operator(!!), but I would prefer to make the compiler to be dynamically aware of the neverNullDataSet to never be nullable.

Thank you in advance for your help!

0

There are 0 best solutions below