Wesley Acheson
06/19/2020, 11:36 AMOptional<String>.map(...).orElse(null)
I'm currently writing this if (source.mpi.dsEndProtocolVersion!= null) Version(source.mpi.dsEndProtocolVersion!!) else null
but that doesn't feel right to me.
Nullable String to nullable Versiondiesieben07
06/19/2020, 11:38 AMsource.mpi.dsEndProtocolVersion?.let { Version(it) }
Wesley Acheson
06/19/2020, 11:39 AMlet
makes me think of variable declaration in BASICJoost Klitsie
06/19/2020, 2:53 PM!!
val dsEndProtocolVersion = source.mpi.dsEndProtocolVersion
if (dsEndProtocolVersion != null) {
Version(dsEndProtocolVersion)
} else {
null
}
the let
lets you do this without needing to assign the local variable, making it better readable and cleaner to use.Wesley Acheson
06/19/2020, 2:58 PMJoost Klitsie
06/19/2020, 2:59 PMWesley Acheson
06/19/2020, 3:00 PMJoost Klitsie
06/19/2020, 3:04 PMval myString: String? = "a value"
get() {
field?.let {
field = null
return it
}
}
This is perfectly valid kotlin code (as an example of course, I wouldn't see the actual need for it 😄 )
if (myString != null) println(myString!!)
This would now crash.
So your warning is not a warning, it is an essential error as Kotlin wants your code to be null safe and it has to take into account fields are prone to change.Wesley Acheson
06/19/2020, 3:05 PMJoost Klitsie
06/19/2020, 3:08 PMWesley Acheson
06/19/2020, 3:10 PMJoost Klitsie
06/19/2020, 3:13 PMWesley Acheson
06/19/2020, 3:14 PMJoost Klitsie
06/19/2020, 3:15 PMWesley Acheson
06/19/2020, 3:15 PM