https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
w

william

09/28/2020, 12:44 PM
is there anyway to achieve an
actual
value in an
expect class
which references a value not given yet? for example I want to achieve
Copy code
val incoming: ReceiveChannel<Frame>
val incomingText: Flow<String> = incoming.consumeAsFlow().filter { it is Frame.Text }.map { (it as Frame.Text).payload }
where
incomingText
is basically a convenience method to give to consumers of that class. the error here states
Expected property cannot have an initializer
i can implement
incomingText
as an extension function but that seems weird
f

flosch

09/28/2020, 12:52 PM
extension function is the way to go here afaik. expected declarations cannot have a body
w

william

09/28/2020, 12:54 PM
alright well thats good enough for now then
j

Joffrey

09/29/2020, 11:58 AM
The error seems to be about the initializer, so wouldn’t
get()
work here?
Copy code
val incoming: ReceiveChannel<Frame>
val incomingText: Flow<String>
  get() = incoming.consumeAsFlow().filter { it is Frame.Text }.map { (it as Frame.Text).payload }
As an aside @william you woudn’t need the cast if you used
filterIsInstance<Frame.Text>()
:
Copy code
val incomingText: Flow<String>
  get() = incoming.consumeAsFlow()
                  .filterIsInstance<Frame.Text>()
                  .map { it.payload }
w

william

09/29/2020, 12:01 PM
interesting let me try that
f

flosch

09/29/2020, 12:02 PM
No it would not work, since this is also a declaration body
👍 1
w

william

09/29/2020, 12:02 PM
still getting an error there "Expected declaration must not have a body"
👍 1
j

Joffrey

09/29/2020, 12:03 PM
Fair enough then. If you have to declare an extension, you can also declare an extension property (not necessarily an extension function).
👍 1
w

william

09/29/2020, 12:03 PM
does this somehow relate to why so many ktor and some Flow functions are written as extensions functions?
j

Joffrey

09/29/2020, 12:06 PM
I think the reason for that would mostly be because Kotlin designers thrive for extension-oriented design (especially in coroutines). But this is related: basically the principle is to declare the core of your interface as real properties/methods, and all the “convenience” stuff should only be extensions. Since the
expect/actual
mechanism is about implementing the core of the logic on each platform, it is sort of by definition that the rest (common code) is just “convenience”.
w

william

09/29/2020, 12:08 PM
awesome an article from Roman. that makes sense, its interesting to see libraries be used like this more - seems like a step further into kotlin rather than improved java
35 Views