💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
[TOC] ## 重载get操作符 ```kotlin /** * public interface Context { * public interface Key<E extends Element> { * } * * @Nullable * <E extends Element> E get(@NotNull Key<E> key); * * public interface Element extends Context { * @NotNull * Key<?> getKey(); * * @Override // org.example.Context * @Nullable * <E extends Element> E get(@NotNull Key<E> key); * * public static final class DefaultImpls { * @Nullable * public static <E extends Element> E get(@NotNull Element element, @NotNull Key<E> key) { * Intrinsics.checkNotNullParameter(key, "key"); * if (!Intrinsics.areEqual(element.getKey(), key)) { * return null; * } * Intrinsics.checkNotNull(element, "null cannot be cast to non-null type E of org.example.Context.Element.get"); * return element; * } * } * } * } */ interface Context { public operator fun <E : Element> get(key: Key<E>): E? public interface Key<E : Element> public interface Element : Context { public val key: Key<*> public override operator fun <E : Element> get(key: Key<E>): E? = @Suppress("UNCHECKED_CAST") if (this.key == key) this as E else null } } /** * public interface ITask extends Context.Element { * * @NotNull * public static final Key Key = Key.$$INSTANCE; * * void test(); * * public static final class DefaultImpls { * @Nullable * public static <E extends Context.Element> E get(@NotNull ITask iTask, @NotNull Context.Key<E> key) { * Intrinsics.checkNotNullParameter(key, "key"); * return (E) Context.Element.DefaultImpls.get(iTask, key); * } * } * * /* compiled from: Main.kt */ * /* loaded from: ITask$Key.class */ * public static final class Key implements Context.Key<ITask> { * static final /* synthetic */ Key $$INSTANCE = new Key(); * * private Key() { * } * } * } */ public interface ITask : Context.Element { // compaion object 伴生对象,可以是接口,提供默认实现 public companion object Key : Context.Key<ITask> fun test() } /** * public final class Test implements ITask { * @Override // org.example.Context.Element, org.example.Context * @Nullable * public <E extends Context.Element> E get(@NotNull Context.Key<E> key) { * return (E) ITask.DefaultImpls.get(this, key); * } * * @Override // org.example.ITask * public void test() { * System.out.println((Object) "call test"); * } * * @Override // org.example.Context.Element * @NotNull * public Context.Key<?> getKey() { * return ITask.Key; * } * } */ class Test : ITask { override fun test() { println("call test") } override val key: Context.Key<*> get() = ITask } /** * public final class MainKt { * public static final void main() { * Context test = new Test(); * ITask iTask = (ITask) test.get(ITask.Key); * if (iTask != null) { * iTask.test(); * } * } * } */ fun main() { val test: Context = Test() test[ITask]?.test() // 等价于(test.get(ITask) as? ITask)?.test() } ```