Multik 0.3.0 Help

Type casting

Overview

Type casting changes the dtype of an ndarray while preserving its shape and dimension. Multik provides two primary APIs:

  • asType<T>() on NDArray

  • toType<T>() on MultiArray

Both create a new array with converted element values.

asType on NDArray

asType is a simple way to cast an NDArray to a new numeric type. It preserves shape and dimension.

val a = mk.ndarray(mk[1, 2, 3]) val b = a.asType<Double>() // dtype is Double, values are [1.0, 2.0, 3.0]

You can also cast using a DataType:

val a = mk.ndarray(mk[1, 2, 3]) val c = a.asType<Float>(DataType.FloatDataType)

toType on MultiArray

toType works for any MultiArray and supports copy strategies. It can be useful when you are working with views or with arrays that are not consistent.

val m = mk.ndarray(mk[mk[1, 2], mk[3, 4]]) val d = m.toType<Int, Double, D2>()

Copy strategies

toType accepts a CopyStrategy:

  • CopyStrategy.FULL (default) copies the entire underlying storage.

  • CopyStrategy.MEANINGFUL copies only the visible elements of the array.

val view = m[0] // view of the first row val fullCopy = view.toType<Int, Double, D1>(CopyStrategy.FULL) val meaningfulCopy = view.toType<Int, Double, D1>(CopyStrategy.MEANINGFUL)

Use MEANINGFUL when you want to materialize just the data visible through a view. Use FULL when you want to preserve the full underlying storage layout.

Casting to complex types

Numeric arrays can be converted to complex types; the imaginary part is set to zero:

val real = mk.ndarray(mk[1.0, 2.0]) val complex = real.toType<Double, ComplexDouble, D1>()

Conversions between complex types are supported as well.

Notes and tips

  • Casting always creates a new array; it does not modify the original.

  • When the dtype is already the target type, toType returns a copy based on the chosen strategy.

19 February 2026