【问题标题】:Generic Constraint of Multiple Types多种类型的泛型约束
【发布时间】: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 是否支持与此等效的功能?

【问题讨论】:

    标签: kotlin generics


    【解决方案1】:
    class Baz<T>(x: T) where T : Foo, T : Bar {
        init {
            println(x.a)
            println(x.b)
        }
    }
    

    【讨论】:

    • 哇...好吧我没想到! XD
    猜你喜欢
    • 1970-01-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多