Martin Barth
10/29/2020, 2:52 PMfun convertMaybe(record: Record?): DataObject? {
return if (record != null) converter.buildDataObject(record) else null
}
natpryce
10/29/2020, 2:53 PMMartin Barth
10/29/2020, 2:57 PMMartin Barth
10/29/2020, 2:57 PMnatpryce
10/29/2020, 2:58 PMrecord?.let { converter.buildDataObject(it) }
natpryce
10/29/2020, 2:59 PM(Record)->DatObject
and basically mean the same thing.Martin Barth
10/29/2020, 3:00 PMMartin Barth
10/29/2020, 3:01 PMRob Elliot
10/29/2020, 3:28 PMfun Record.toDataObject(): DataObject = converter.buildDataObject(this)
val record: Record? = TODO("either null or not null")
val dataObject: DataObject? = record?.toDataObject()
Like let
, allows you to use standard null safe calls to avoid ugly if/else logic, but sometimes in a more readable way. And means that the signature of your method is nice and simple - neither takes nor returns null, so doesn’t need a special name.Nir
10/29/2020, 3:29 PMconvertOrNull
Nir
10/29/2020, 3:29 PMMartin Barth
10/29/2020, 3:33 PMRob Elliot
10/29/2020, 3:47 PMconvertOrNull
would be an idiomatic name for the extension function. It is neither called on a null type nor does it return a null type; the null safe call means that if the record is null the extension function is not called at all.
I would use toDataObject
as describing what the conversion results in returning; this fits with e.g. fun <T> Array<out T>.toList(): List<T>
in the stdlib.Martin Barth
10/29/2020, 3:51 PMRob Elliot
10/29/2020, 3:51 PMMartin Barth
10/29/2020, 3:52 PMMartin Barth
10/29/2020, 3:52 PM