https://kotlinlang.org logo
a

Artur Matsehor

10/03/2020, 9:11 PM
Hi Is there a way to make data classes with default parameter values work properly in Swift? Example:
Copy code
data class State @JvmOverloads constructor(
    val loading: Boolean = false,
    val data: ResponseBody? = null,
    val error: ApiError? = null
)
In Swift, it is resolved to
init(loading: Bool, data: ResponseBody?, error: ApiError?)
Neither with overloads or default values
👀 1
d

dazza5000

10/04/2020, 3:00 AM
Are you creating a framework?
m

Madhan

10/04/2020, 5:48 AM
@Artur Matsehor I'm also facing same problem. In Xcode it throws error as "init is unavailable". let me know if you found solution for this. Thanks in advance
👍 1
a

Artur Matsehor

10/04/2020, 7:57 AM
@dazza5000 yes
Basically, I'm making a project with business-logic written in Kotlin, leaving only UI and VMs on a platform side. Pretty usual case for KMP, as I understand.
@Madhan now I kinda solve it by creating functions like
*func* State(loading: Bool = *false*, data: ResponseBody? = *nil*, error: ApiError? = *nil*) -> State {
  
.init(loading: loading, data: data, error: error)
}
Which is against Swift conventions and is a boilerplate, but still better than nothing
m

Madhan

10/04/2020, 1:30 PM
Okay @Artur Matsehor , But Here is my suggestions
Copy code
class State {
    var loading: Boolean = false,
    var data: ResponseBody? = null,
    var error: ApiError? = null

    constructor()

    constructor(loading: Boolean = false,
                 data: ResponseBody? = null,
                 error: ApiError? = null) {
        this.loading = loading
        this.data = data
        this.error = error
    }
}
Look into it and let me know your thoughts
a

Artur Matsehor

10/04/2020, 6:48 PM
Legit, but still a part of a solution Say, I need a
let state = State(data: responseData)
- it is still impossible( Also, here we're losing all the data class sweeties, like toString(), hashCode(), componentN(), etc
👍 1
I'm really thinking of making a Gradle plugin that generates all the constructor overloads before converting a class into a Swift framework
❤️ 1
@Madhan you can watch this issue on Youtrack also https://youtrack.jetbrains.com/issue/KT-38685
m

Madhan

10/05/2020, 10:30 AM
sure @Artur Matsehor ,thanks for sharing
12 Views