5

What happens is that "mystring".toCharArray() returns a CharArray but I need an Array<Char>.

  1. Why CharArray exists? what's the idea behind it?
  2. How can I cast a CharArray to Array<Char>?

I found one way to make it Array<Char>

"mystring".toCharArray().map { it }.toTypedArray()

but is there any other way to do it?

2 Answers 2

8

For the first part of your question, refer to the "Basic types" section of the official language documentation:

Kotlin also has specialized classes to represent arrays of primitive types without boxing overhead: ByteArray, ShortArray, IntArray and so on. These classes have no inheritance relation to the Array class, but they have the same set of methods and properties. Each of them also has a corresponding factory function:

For the second part of your question, it seems you don't need the map. You can just do:

"mystring".toCharArray().toTypedArray()
Sign up to request clarification or add additional context in comments.

Comments

1

Another way is mapping the CharSequence to it which will give you a List<Char> which then can be converted to the desired Array<Char>:

"mystring".map { it }.toTypedArray()

1 Comment

another alternative: "hello".toList().toTypedArray()

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.