Search code examples
swiftkotlininterfaceprotocolsswift-protocols

Is there a way to do Swift's Protocol Composition in Kotlin


So for Swift we can create new types or pass to a method as a parameters using the & operator.

Example Swift Code:

protocol Fooable {}
protocol Barable {}

// the new protocol
typealias FooBarable = Fooable & Barable

// method parameter 
func doSomethingFor(object: Fooable & Barable) { ... }

Is there a way to do this in Kotlin's Interfaces?


Solution

  • Please check the below code:

    interface A{
    
    }
    
    interface B{
    
    }
    
    fun <T> check(variable: T) where T : A, T: B{
        print("Hello");
    }
    

    the above gives you compile time error if you try to pass a variable which doesn't confirm to both of them