Does Kotlin Support or Have Future Plan for Interface Composition Similar to Protocol Composition in Swift

Does Kotlin support or have future plan for Interface Composition similar to Protocol Composition in Swift?

You can not explicitly define intersection types in Kotlin, but you can use generic type constraints to achieve it in a function parameter. Like this:

interface Named {
val name: String
}

interface Aged {
val age: Int
}

fun <T> wishHappyBirthday(celebrator: T) where T : Named, T : Aged {
println("Happy birthday, ${celebrator.name}, you're ${celebrator.age}!")
}

Typealias - Combine Multiple Interfaces in Kotlin

Why not just create new interface?

interface MyType : ReadableInterface, WritableInterface

What is the difference between loose coupling and tight coupling in the object oriented paradigm?

Tight coupling is when a group of classes are highly dependent on one another.

This scenario arises when a class assumes too many responsibilities, or when one concern is spread over many classes rather than having its own class.

Loose coupling is achieved by means of a design that promotes single-responsibility and separation of concerns.

A loosely-coupled class can be consumed and tested independently of other (concrete) classes.

Interfaces are a powerful tool to use for decoupling. Classes can communicate through interfaces rather than other concrete classes, and any class can be on the other end of that communication simply by implementing the interface.

Example of tight coupling:

class CustomerRepository
{
private readonly Database database;

public CustomerRepository(Database database)
{
this.database = database;
}

public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}

class Database
{
public void AddRow(string Table, string Value)
{
}
}

Example of loose coupling:

class CustomerRepository
{
private readonly IDatabase database;

public CustomerRepository(IDatabase database)
{
this.database = database;
}

public void Add(string CustomerName)
{
database.AddRow("Customer", CustomerName);
}
}

interface IDatabase
{
void AddRow(string Table, string Value);
}

class Database implements IDatabase
{
public void AddRow(string Table, string Value)
{
}
}

Another example here.



Related Topics



Leave a reply



Submit