Hey guys, what is the main difference between `exp...
# multiplatform
e
Hey guys, what is the main difference between
expect class
and an
interface
, defined in the common part? It looks like in both cases I can define signature in the common code and then implement platform specific implementation. What is the main point of using
expect class
instead?
j
• Another class cannot inherit multiple classes, so you can limit what your code can do. • A class can have state, an interface cannot.
e
@Javier it looks like one can’t declare any state in expect classes. I can add fields the same way I can declare them in an interface.
a
Expect class can declare a constructor and can be instantiated from the common sourceset. Implemented interfaced can only be created in platform source sets and injected to common. I prefer interfaces over expect classes as it provides more flexibility and abstraction and easier to test.
The most important rn to know is that expect/actual classes are in Beta.
e
@Alexander Zhirkevich In the most of cases what I saw, expect classes were used in situation, when platform specific implementation required extra some extra information. The most common case: Context in Android. And the actual class just implemented a constructor with
Context
or something like that. I don’t understand if are there any advantages of
expect class
over regular interface in this case.
p
Usual pattern is instead of expect class, to use normal interface and expect funs (it's in the docs and default sample for kmp.jetbrains.com + AS demo
e
@Pamela Hill For me it is not totally clear from this doc if there are any other cases, when expect classes can be useful. There are some in the doc, like already existing platform type. But it is not clear if this list is exhaustive.
And it looks like some library maker also don’t understand that difference and use expect classes instead of interfaces sometimes.
So as I understood from this discussion, besides some corner cases, described in the doc, the only reason of using
expect class
is the case, when one needs to instantiate the class inside the common code and DI is not possible or convenient (like creating exception). In all other cases when we can inject platform-specific implementation into the common code or are creating the instance in the platform code it is much correct to use interfaces.
I don’t see any reason of using
expect class
here.
@Pamela Hill One more interesting thing in defence of
expect class
. There is a pretty nice support from the IDE side when we use them instead of interfaces: one can see if the class has or not implementations on all platforms and allows to quickly create one, creating all required directories and files.
v
And I like the naming convention where the actual file name is Foo.ios.kt Foo.android.kt It's much easier finding the correct implementation.