Conceptually I want to do this:
// Expect file (commonMain)
expect class PlatformDir
// Platform-specific implementation for JVM
actual typealias PlatformDir = File
// Platform-specific implementation for Linux/macOS
actual typealias PlatformDir = CPointer<DIR>
The simple JVM type is accepted but the parameterized type of Linux/macOS is not:
Expected class 'PlatformDir' has no actual declaration in module for Native The following declaration is incompatible because number of type parameters is different: public actual typealias PlatformDir = CPointer
Type arguments in the right-hand side of actual type alias should be its type parameters in the same order, e.g. 'actual typealias Foo<A, B> = Bar<A, B>'
Actual typealias 'PlatformDir' has no corresponding expected declaration The following declaration is incompatible because number of type parameters is different: public final expect class PlatformDir
Moving the parameterized type first into its own typealias also doesn't work:
private typealias CPointer_DIR = CPointer<DIR>
actual typealias PlatformDir = CPointer_DIR
It still complains about the wrong number of type parameters and has this additional error:
Right-hand side of actual type alias should be a class, not another type alias
I'm very much a noob in Kotlin and JVM as well as Kotlin Multiplatform so I feel this must be possible without wrapping both in a class. Googling I can't find anybody discussing this and the AI chatbots seem to just clutch at straws that get more and complex and don't build either.
1条答案
按热度按时间tyg4sfes1#
你试图在JVM中使用简单类型,在Native平台中使用参数化类型,但不幸的是,Kotlin不支持在expect和actual声明中使用不同数量的类型参数。
但是,您可以通过稍微不同的方法来实现所需的结果,在expect声明中使用泛型类,然后提供实际的实现。下面是一个例子:
在本例中,您在expect声明中使用了一个泛型类,然后为每个平台提供实际的实现。对于JVM,类型参数T实际上并没有被使用,而对于Native平台,它被按预期使用。
请记住,这种方法可能会有些混乱,因为类型参数T在JVM实现中实际上并不是必需的。它更像是一种维护不同平台之间兼容性的变通方法。