Skip to content

Latest commit

 

History

History
43 lines (30 loc) · 1.13 KB

Generic classes.md

File metadata and controls

43 lines (30 loc) · 1.13 KB

Generic classes

Some features are supported.

Explanations

Let's describe a generic class in Kotlin:

class StateHolderWithoutAny<T>(data: T) {
    val myState = data
    fun pullState(): T = myState
}

You can't make generics over basic types. The interop is carried out through Objective-C, which does not allow this to be done.

What types cannot be substituted:

  • Int / Int8 / Int16 / Int32 / Int64
  • Float / Double
  • String
  • Bool

But you can get NSNumber by NSString.

Another feature is related to nullability - similar to generic functions. The type T is interpreted as Any?, so additional unwrapping has to be introduced:

let result1: NSString = StateHolderWithoutAny<NSString>(data:"'222'").pullState()!

In order for Swift to see that the type is definitely not null, you need to use the boundary syntax on the Kotlin side:

class StateHolderWithAny<T : Any>(data: T) {
    val myState = data
    fun pullState(): T = myState
}

Table of contents