Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

  • Kotlin Interfaces Documentation
  • Swift Protocols Documentation
like image 683
Zonily Jame Avatar asked Jan 01 '23 20:01

Zonily Jame


2 Answers

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

like image 147
Sahil Avatar answered Jan 03 '23 09:01

Sahil


From the function side you'd be able to handle it with generic functions using a where-clause:

fun <T> foo(obj: T) where T: Fooable, T: Barable {
    ...
}
like image 38
tynn Avatar answered Jan 03 '23 11:01

tynn