Unchecked casts in public initMemoryView API
- Dominant language
- Kotlin
- Stars
- 734
- Forks
- 51
- Avg merge
- 9h 52m
- Merged PRs (30d)
- 6
Description
The public `initMemoryView` functions in `multik-core/src/commonMain/kotlin/org/jetbrains/kotlinx/multik/ndarray/data/MemoryView.kt` rely on unchecked casts across every `DataType` branch:
```kotlin
// MemoryView.kt:1058
@Suppress("UNCHECKED_CAST")
public fun initMemoryView(size: Int, dataType: DataType, init: (Int) -> T): MemoryView {
val t = when (dataType) {
DataType.ByteDataType -> MemoryViewByteArray(ByteArray(size, init as (Int) -> Byte))
// ... 7 more branches, each with an unchecked cast
}
return t as MemoryView
}
```
The same pattern appears in the zero-init overload (`MemoryView.kt:1035`). The relationship between `T` and `dataType` is an unchecked invariant — passing mismatched arguments produces a `ClassCastException` on the first element access.
This is part of a broader pattern (see also #251 for `NDArray.asType`). In Kotlin stdlib, such casts are hidden behind `@PublishedApi internal` with documented invariants; here they sit on the public API surface.
### Proposal
- Move the unchecked-cast implementation behind `@PublishedApi internal` and expose a safe `reified` overload that derives `dataType` from `T`.
- Or: document the `T`/`dataType` invariant explicitly and add a debug-time check.
- Audit other public functions for the same pattern.
Contributor guide
Research direction
Start with both public initMemoryView overloads at lines 1035 and 1058 in multik-core/src/commonMain/kotlin/org/jetbrains/kotlinx/multik/ndarray/data/MemoryView.kt, then compare the related pattern in issue #251. Determine which proposed API-safety direction fits the project, audit the other public functions mentioned, and verify that the T/DataType invariant is either enforced or explicitly documented without the current public unchecked-cast pattern.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- kotlin
- Domain
- api
- Issue type
- Refactor
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Quiet
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100