1

I am new to kotlin and I am facing this issue

I have an ArrayList<String?> and I have to pass it to a function that accepts List<CharSequence> I tried to find a way to convert them but couldnt, How can I convert ArrayList<String?> to List<CharSequence> in kotlin

1
  • 1
    In view of Tenfour04's comment: what should happen if the ArrayList contains any nulls?  Should it ignore them, and create a List with only the non-null items, or should it give a runtime exception?  (Also, it's customary to wait rather more than 10 minutes before accepting an answer, to give people in other parts of the world a chance… and to ensure that the answer you accept does actually answer the question fully!) Commented Feb 21, 2021 at 14:34

2 Answers 2

4

Use

val list: List<CharSequence> = arrayList.filterNotNull()

filterNotNull() removes any possible null values so you have a List<String>, which can be automatically up-cast to a List<CharSequence>.

Sign up to request clarification or add additional context in comments.

Comments

0

CharSequence is an interface and String class is already implemented that. Hence cast to CharSequence should be enough. map function returns List<T>

val list = arrayList.map { it as CharSequence }

With filtering null values

val list: List<CharSequence> = arrayList.filterNotNull() 

4 Comments

This will crash if there are any null values in the source list.
You can filter null values before converting. I updated my answer.
The map { it } call is entirely redundant.
@Tenfour04 Yes filterNotNull already returns List<T>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.