Kotlin List toDoubleArray()
Syntax & Examples


Syntax of List.toDoubleArray()

The syntax of List.toDoubleArray() extension function is:

fun Collection<Double>.toDoubleArray(): DoubleArray

This toDoubleArray() extension function of List returns an array of Double containing all of the elements of this collection.



✐ Examples

1 Example

In this example,

  • We create a list named list containing the doubles 1.0, 2.5, 3.7.
  • We call the toDoubleArray() function on list.
  • The resulting array of doubles is stored in result.
  • Finally, we print the array elements to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf(1.0, 2.5, 3.7);
    val result = list.toDoubleArray();
    println(result.joinToString(", "));
}

Output

1.0, 2.5, 3.7

2 Example

In this example,

  • We create a list named list containing the characters 'a', 'b', 'c'.
  • We call the toDoubleArray() function on list.
  • The resulting array of doubles is stored in result.
  • Finally, we print the array elements to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf('a', 'b', 'c');
    val result = list.toDoubleArray();
    println(result.joinToString(", "));
}

Output

97.0, 98.0, 99.0

3 Example

In this example,

  • We create a list named list containing the strings "apple", "banana", "cherry".
  • We call the toDoubleArray() function on list.
  • The resulting array of doubles is stored in result.
  • Finally, we print the array elements to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list = listOf("apple", "banana", "cherry");
    val result = list.toDoubleArray();
    println(result.joinToString(", "));
}

Output

e: /Users/programguru/IdeaProjects/KotlinExample/src/main/kotlin/main.kt: (3, 23): Unresolved reference. None of the following candidates is applicable because of receiver type mismatch: 
public fun Array<out Double>.toDoubleArray(): DoubleArray defined in kotlin.collections
public fun Collection<Double>.toDoubleArray(): DoubleArray defined in kotlin.collections

Summary

In this Kotlin tutorial, we learned about toDoubleArray() extension function of List: the syntax and few working examples with output and detailed explanation for each example.