https://kotlinlang.org logo
#announcements
Title
# announcements
p

Paul Woitaschek

06/27/2019, 8:17 AM
For extension functions. When do you use the prefix
as
and when do you use the prefix
to
?
r

ribesg

06/27/2019, 8:19 AM
I feel like
as
would be some kind of cast while
to
would be a transformation
👆 3
👍 1
m

marstran

06/27/2019, 8:20 AM
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

ribesg

06/27/2019, 8:20 AM
Yeah there’s also the idea that
to
basically costs more than
as
. It’s more complex.
t

Toddobryan

06/27/2019, 8:20 AM
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

Paul Woitaschek

06/27/2019, 8:23 AM
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

gildor

06/27/2019, 8:31 AM
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

Paul Woitaschek

06/27/2019, 8:35 AM
Thanks for your input; naming is hard 🙂
2 Views