多种类型的通用约束

ser*_*0ne 4 generics kotlin

在 Kotlin 中,我可以创建类型的通用约束T;例如:

interface Foo {
  val a: String
}

class Baz<T : Foo>(x: T) {
  init {
    println(x.a)
  }
}
Run Code Online (Sandbox Code Playgroud)

我想要的是一个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);
  }
}
Run Code Online (Sandbox Code Playgroud)

C# 中的等效项是使用IFooand的通用约束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);
  }
}
Run Code Online (Sandbox Code Playgroud)

Kotlin 是否支持与此等效的功能?

IR4*_*R42 7

class Baz<T>(x: T) where T : Foo, T : Bar {
    init {
        println(x.a)
        println(x.b)
    }
}
Run Code Online (Sandbox Code Playgroud)