Anyone has exp dealing with Kotlin sealed classes ...
# multiplatform
j
Anyone has exp dealing with Kotlin sealed classes + Generics working in Swift? I’m struggling a bit to find a good implementation e.g
Copy code
sealed class Result<T> {
  Success(val data: T): Result()
  Error(val message: T): Result()
}
How would you switch case with a swift optional + handle both success and error cases?
j
Maybe a fold function based on callbacks, Kotlin usage: someResult.fold( success = { data -> doSomething(data) }, error = { message -> println(message) }, )
s
To
switch
over a sealed class you can use:
Copy code
switch result{
    case let success as ResultSuccess:
        print("success")
    case let failure as ResultFailure:
        print("failure")
    default:
        break //Swift will require an exhaustive switch
}
I think but am not positive that you could include type parameters on those
let
lines.
👍 2
j
Thank you @Sam @Javier for your input(s) I’ll try it out and give some feedback here 🙏
It worked @Sam, your implementation works 😉 Followup Q have you gotten sealed class working correctly with Swift? For some context, I have a ViewState that has various class (Loading, Idle, Success etc.) as a sealed class, but now when I declare a variable as a ViewState I can’t set it
s
I haven’t run into that issue. Have a look at your module header (cmd+click on a Kotlin class in a Swift file to easily get there) and verify that your sealed classes are show as inheriting from the base sealed class. Something like:
Copy code
@interface MyModule_modulePrefixLoading : MyModule_modulePrefixViewState
If that is not there, then maybe your Kotlin definition is off and the sealed classes aren’t inheriting from a common base.
j
It is indeed
Copy code
open class LoginState : KotlinBase {
}
extension LoginState {

    
    public class Error : LoginState {

(other states here)
My issue is I can’t set a variable with another state , let’s say I declare said var in swift:
Copy code
@Published var state: LoginState
now I can’t set it as (for instance) loading
Copy code
state = LoginState.Loading
This is how the shared.swift class is shown