I've used `with` to scope extension functions/prop...
# announcements
b
I've used
with
to scope extension functions/properties defined in an
object
, but thats about all
d
Does it actually look better than
apply
or similar?
b
it's a different application than
apply
, I think it looks good and helps organization, but it's also the only way I know of to access extension methods that aren't top level. For example, in this BLE library, the following object contains some Service specific definitions: https://github.com/Beepiz/BleGattCoroutines/blob/master/genericaccess/src/main/java/com/beepiz/blegattcoroutines/experimental/genericaccess/GenericAccess.kt and they are used like this: https://github.com/Beepiz/BleGattCoroutines/blob/master/common/src/main/java/com/beepiz/blegattcoroutines/sample/common/MainViewModel.kt#L30
d
GenericAccess.apply { }
doesn't work?
But you might be right since
apply
is really more side effectish, whereas
with
is maybe clearer for main logic...
b
you could but conceptually that's weird because you're not "applying" anything to the object or modifying it in any way. You are using it as context or scope, so it looks pretty natural to say "with this scope, do these things"
c
In case when I'm not modifying the receiver, I tend to use
.run
instead of
.apply
to make it clear that I'm just using the scope and running some logic against it.
b
I haven't used
.run
since it become an extension function, but it seems equivalent to `with`:
Copy code
MassTransferService.run {
                enableReceiveBufferIndication()
            }

            with(MassTransferService) {
                enableReceiveBufferIndication()
            }
but I like
with
in this particular case, it just reads more naturally
(note that
enableReceiveBufferIndication()
is not an extension function ON
MassTransferService
, it is defined within the service but acts on a different receiver object (
GattConnection
)
it just looks that way because this is being called inside another extension function on
GattConnection
c
Yes, definitely, I also like to use what reads best all other things being equal 🙂
d
@Czar I didn't notice that one, I mainly thought run was to change the receiver to something else, but you're right that
apply
sounds like you're changing the receiver... @bj0 Where is that (not in what you referenced before)?
b
@dave08 that was a trimmed down snippet from my own code, It's an "init" extension on
GattConnection
and I have several services on the connection, so I use
with
to scope them.
the details are only interesting if you're doing BLE stuff 🙂