Mark
06/02/2022, 2:42 PMtoList()
but then asSequence()
instead of toSequence()
?Joffrey
06/02/2022, 2:43 PMasSomething()
implies that the returned Something
wraps the receiver (or exposes it as a different type), while toSomething()
implies that the new Something
will copy everything it needs from the receiver and have no further relation to it.Mark
06/02/2022, 2:46 PMasSequence()
vs toList()
will return the same items. But I suppose it wouldn’t be expected to do a deep copy, so that’s a moot pointJoffrey
06/02/2022, 2:47 PMtoList()
will create a new list from the existing one, while asSequence()
will only bridge the type but still take its items from the original collection. If you were to change the original collection after conversion, the toList()
variant will not be affected while the asSequence()
result will show the changes:
https://pl.kotl.in/mT9gSB1UcMark
06/02/2022, 2:51 PMtoCollection(destination)
which kind of uses a very different interpretation of to
. I suppose it maintains the philosophy of to
being unaffected by changes to the originalJoffrey
06/02/2022, 2:53 PMtoList
. The only difference is that you provide the new collection yourself instead of letting the function create it. But I agree the collection will not necessarily be "new' in that case.
I find the as-
prefix pretty neat because it aligns with the casting operator as
, which is really hinting towards the fact that we express the object as a different type, but it's really the same object behind the scenes.ephemient
06/02/2022, 3:35 PMval a = mutableListOf("hello", "world")
val b = a.asReversed()
assert(b == listOf("world", "hello"))
a[0] = "goodbye"
assert(b == listOf("world", "goodbye"))
val c = listOf(1)
val d = c.toIntArray()
assert(d[0] == 1)
c[0] = 2
assert(d[0] == 1)
nkiesel
06/02/2022, 8:16 PMval c = mutableListOf(1)
)Mark
06/06/2022, 1:24 PMfun CharSequence.asSpannableStringBuilder() =
this as? SpannableStringBuilder ?: SpannableStringBuilder(this)
and that we should prefer:
fun CharSequence.toSpannableStringBuilder() = SpannableStringBuilder(this)
Either way, you shouldn’t use the original receiver because it contains spans that are now used by the returned object because spans are not allowed to be used in multiple builders.ephemient
06/06/2022, 1:29 PMMark
06/06/2022, 1:29 PMNoCopySpan
ephemient
06/06/2022, 1:30 PMMark
06/06/2022, 1:34 PMSpannedString(builder)
rather than the SpannableStringBuilder
itself, for example as a CharSequence
On another Android-specific (and non-Kotlin!) note I see that SpannedString
does:
public static SpannedString valueOf(CharSequence source) {
if (source instanceof SpannedString) {
return (SpannedString) source;
} else {
return new SpannedString(source);
}
}
ephemient
06/06/2022, 1:36 PMSpannedString
is immutable so that's fineMark
06/06/2022, 1:41 PMSpannedString
is a better return type than CharSequence