“When should one prefer using CharSequence over St...
# getting-started
h
“When should one prefer using CharSequence over String?”
s
The only time I've found it useful is when I want to let people pass in a
StringBuilder
. It doesn't come up very often.
c
String
is a specific implementation in memory, in which all chars are stored consecutively in memory.
CharSequence
, however, does not give any requirements with regards to storage, so you could construct a CharSequence from an input stream, etc. However,
CharSequence
instances are unsafe for comparison, so it's unsafe to put as a key in a map, etc, so it's quite limited.
h
So we can use it for memory optimisation when working with large data
c
It could be useful for streaming data, but if you're streaming data you're probably using InputStream/OutputStream instead…
Honestly, it's not used much
k
In Kotlin, the CharSequence interface defines a
get(index)
method with the implication that repeated calls to
get(n)
will retrieve the same character, so it can't be used to stream data from an InputStream unless you cache every character read so far.
c
Oh, indeed.