is there a nicer way to write this: ``` fun con...
# announcements
m
is there a nicer way to write this:
Copy code
fun convertMaybe(record: Record?): DataObject? {
        return if (record != null) converter.buildDataObject(record) else null
    }
n
record?.let(converter::buildDataObject)
🆒 1
m
why does it pass record/this into the method?
and thanks this is cool!
n
It’s the same as:
record?.let { converter.buildDataObject(it) }
the bound method reference syntax (converter::buildDataObject) and the lambda are both functions of type
(Record)->DatObject
and basically mean the same thing.
👍 3
m
ah!
awesome! thanks for the explanation
r
Consider an extension function:
Copy code
fun 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.
👍🏻 2
n
The idiomatic name for such an extension function might be
convertOrNull
unless it is already obvious that a null can result
m
thanks
r
I disagree that
convertOrNull
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.
☝🏻 2
m
the extension function would be lexical scoped? so is only available within the class where i define the extention fun?
r
To have access to your converter value, yes
m
makes sense 🙂
thanks for your help