Search code examples
swiftgenericsinterfacekotlinprotocols

Swift to Kotlin: Protocol to Interface, with generics


Been working at this small code translation over the past couple days. It's really just Kotlin syntax stumping me...

Swift:

protocol BaseProtocol {
    associatedtype VMType = BaseViewModel
    var viewModel: VMType { get set }
}

public class BaseViewModel {
    var moduleModel: ModuleModel
    required public init(moduleModel: ModuleModel) {
        self.moduleModel = moduleModel
    }
}

Here's what I've brought over to Kotlin, (it's the Protocol to interface stumping me, primarily with regards to the generics)

Kotlin:

interface BaseInterface<VMType> {    // Not sure if this is correct
    // protocol code...
}

class BaseViewModel(internal var moduleModel: ModuleModel)

I believe I have structured my BaseViewModel properly, but if that needs adjustment I am all ears, as well.

Thanks in advance for any advice!


Solution

  • I am not a swift programmer so correct me if I'm wrong. Is your protocol type bounded to the BaseViewModel class? If yes you can declare a bounded type in your interface as well.

    interface BaseInterface<T : BaseViewModel>
    

    And also, since you are bounded on the BaseViewModel class, be sure to set it as inheritable by adding the open modifier.

    open class BaseViewModel(var moduleModel: ModuleModel)