【发布时间】:2020-12-08 07:53:26
【问题描述】:
在 Kotlin 中,我可以创建 T 类型的通用约束;例如:
interface Foo {
val a: String
}
class Baz<T : Foo>(x: T) {
init {
println(x.a)
}
}
我想要的是一个通用约束,T 扩展或实现了多种类型。
TypeScript 中的等价物是使用交集类型;例如:
interface Foo {
a: string;
}
interface Bar {
b: number;
}
class Baz<T extends Foo & Bar> {
constructor(x: T) {
console.log(x.a);
console.log(x.b);
}
}
C# 中的等价物是使用IFoo 和IBar 的通用约束;例如:
public interface IFoo
{
string A { get; }
}
public interface IBar
{
string B { get; }
}
public class Baz<T> where T : IFoo, IBar
{
public Baz(T x)
{
Console.WriteLine(x.A);
Console.WriteLine(x.B);
}
}
Kotlin 是否支持与此等效的功能?
【问题讨论】: