KMM generics in Swift: force KMM Any to be Swift Any instead of AnyObject

Viewed 399

I'm currently working on a KMM library that is implemented in Swift. So there's something I don't really get with generics.

I have my KMM generic class:

class Foo<T> {
 ...
}

Then, i can use it without any problem in KMM, for example like that

var bar = Foo<List<SomeClass>>()

The original problem:

This is a little different when I use it in swift, cause when I compile my KMM lib as a Swift Framework, my class is now declared this way:

public class Foo<T> : KotlinBase where T : AnyObject {
 ...
}

And here, I cannot use it with Arrays as I do in KMM because a Swift Array is not Any but AnyObject. For example:

var bar = Foo<[SomeClass]>()

and then i got the error:

'Foo' requires that '[AnyObject]' be a class type

Question:

Is it possible to force something so that KMM Any is interpreted in Swift as Any and not AnyObject, or is there another solution to this problem ?

EDIT:

As Alexander said:

There's probably no way to work around this. Fundamentally, the JVM lacks a way to express in-place allocated value types like Swift's structs or enums, besides the handful of primitives that are hardcoded into the platform.

So I tried to make an overload of Foo in KMM like that:

class ListFoo<T>() : Foo<T>() where T: List<Any> {}

and then compile it as Swift Framework (I set Foo as open class btw).

So I was expecting that my ListFoo class in Swift looked like something like that:

public class ListFoo<T> : Foo<T> where T : [Any] {
  public init()
}

But I the class I found was something more... well annoying:

 public class ListFoo<T> : Foo<NSArray> where T : AnyObject {
  public init()
}

Then I made some tests, and I believe that it doesn't matter what type I set for T in my KMM code, T is ALWAYS considered as AnyObject in the Swift Framework.

The final questions:

  • Is there any way to make the compiler understand which type we want for our Generic Type in Swift like Arrays?
  • Is it a KMM issue or a normal issue ?
  • Am I just using generic classes the wrong way ?
0 Answers
Related