For extension functions. When do you use the prefi...
# announcements
p
For extension functions. When do you use the prefix
as
and when do you use the prefix
to
?
r
I feel like
as
would be some kind of cast while
to
would be a transformation
👆 3
👍 1
m
Use
to
if the function transforms something to another type (like putting all elements of a sequence into a list). Use
as
if it will only provide a view over the original object (like a sequence over the original list).
1
r
Yeah there’s also the idea that
to
basically costs more than
as
. It’s more complex.
t
For me, there's no set rule. It feels like
as
implies that the conversion could be implicit (like when Java upcasts an
int
to a
double
, because there's no chance of losing information), but
to
implies that you're having to do some fiddling to get it to work and it could conceivably go wrong.
p
So you think for example
Flowable.asFlow()
should rather be called
Flowable.toFlow()
?
I’m currently reading the OkHttp changelog and they write:
If the returned value is a view of what created is, we use
as
With that reasoning they changed
File.toRequestBody()
->
File.asRequestBody()
g
So you think for example
Flowable.asFlow()
should rather be called
Flowable.toFlow()
Nope, because under the hood it’s still Flowable, so it should be
as
I believe the best example of this convention from stdlib are *Array extensions asList() vs toList(), first uses original array under the hood and List just a view of this array (so changed values of array also changed in list), second copies data and return new instance of List
Yeah there’s also the idea that
to
basically costs more than
as
Mostly because
as
usually does not copying, but it’s not a rule, it’s more like consequence
p
Thanks for your input; naming is hard 🙂