https://kotlinlang.org logo
#ios
Title
# ios
d

Daniele B

09/15/2020, 9:00 AM
Anyone knows why I get this error
init() is unavailable
n

Nikolay Kasyanov

09/15/2020, 9:03 AM
there’s no default arguments in Objective-C, meaning your data class constructor can’t be exactly mapped to Swift
an explicit argumentless constructor or static factory method might help
d

Daniele B

09/15/2020, 9:34 AM
@Nikolay Kasyanov weird, so this happens with all data classes? I have tried to add an argumentless constructor and companion object method, but it still gives me the same error
so, it looks like the problem is with data classes
Copy code
class AppState {
    val masterState : MasterState = MasterState()
    val detailState : DetailState = DetailState()
    val showingDetail : Boolean = false
}
this works fine
n

Nikolay Kasyanov

09/15/2020, 10:15 AM
that’s surprising, default arguments are not properly propagated to Obj-C (and consequently Swift) 🤔
d

Daniele B

09/15/2020, 10:38 AM
I just filed an issue:
n

Nikolay Kasyanov

09/15/2020, 10:48 AM
I wonder how the actual Obj-C header looks like for both types, I bet JB folks would appreciate this too
d

Daniele B

09/15/2020, 11:02 AM
@Nikolay Kasyanov have you ever instantiated data classes on iOS?
n

Nikolay Kasyanov

09/15/2020, 11:03 AM
yes, in some cases we have companion object helper methods to instantiate them with default arguments
then we do
AppState.Companion().initial
in Swift
d

Daniele B

09/15/2020, 11:04 AM
Is there a reason why you use a companion object helper?
n

Nikolay Kasyanov

09/15/2020, 11:05 AM
haven’t tried using an explicit argumentless constructor so dunno, perhaps this approach might cause overload resolution issues on the Kotlin side 🤔
d

Daniele B

09/15/2020, 11:05 AM
Ok, let's see what they find out
In the meantime I solved it with this extra method:
Copy code
data class AppState (
    val masterState : MasterState = MasterState(),
    val detailState : DetailState = DetailState(),
    val showingDetail : Boolean = false,
) {
    companion object {
        fun initState(): AppState {
            return AppState(MasterState(), DetailState(), false)
        }
    }
}
n

Nikolay Kasyanov

09/15/2020, 11:44 AM
I believe you can omit init parameters there to avoid duplicating default values
d

Daniele B

09/15/2020, 11:49 AM
great, it works like this:
Copy code
data class AppState (
    val masterState : MasterState = MasterState(),
    val detailState : DetailState = DetailState(),
    val showingDetail : Boolean = false,
) {
    companion object {
        fun initState(): AppState {
            return AppState()
        }
    }
}
thanks!
n

Nikolay Kasyanov

09/15/2020, 11:50 AM
no probs
6 Views