使用局部类型推断的交叉点类型的有用应用 [英] Useful Applications of Intersection Types using Local Type Inference

查看:107
本文介绍了使用局部类型推断的交叉点类型的有用应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个博客,我们现在可以使用本地类型推断编写以下内容(据我所知,这是以前在不引入更多代码的情况下无法实现的):

As stated by this blog, we are now able to write the following using local type inference (something, to my knowledge, that was previously impossible without introducing more code):

public static void main(String... args) {
    var duck = (Quacks & Waddles) Mixin::create;
    duck.quack();
    duck.waddle();
}

interface Quacks extends Mixin {
    default void quack() {
        System.out.println("Quack");
    }
}

interface Waddles extends Mixin {
    default void waddle() {
        System.out.println("Waddle");
    }
}

interface Mixin {
    void __noop__();
    static void create() {}
}

这个问题可能是太广泛或主要基于意见,但是当利用这样的交叉类型时是否存在任何有用的应用程序?

This question may be either too broad or primarily opinion-based, but do there exist any useful applications when taking advantage of intersection types like this?

推荐答案

交易从Java 5开始,部分未知类型是可能的,所以很容易将你的例子反向移植到Java 8:

Dealing with partially unknown types is possible since Java 5, so it’s quiet easy to backport your example to Java 8:

public static void main(String... args) {
    use((Quacks & Waddles)Mixin::create);
}
private static <Duck extends Quacks & Waddles> void use(Duck duck) {
    duck.quack();
    duck.waddle();
}
interface Quacks extends Mixin {
    default void quack() {
        System.out.println("Quack");
    }
}
interface Waddles extends Mixin {
    default void waddle() {
        System.out.println("Waddle");
    }
}
interface Mixin {
    void __noop__();
    static void create() {}
}

所以有可能做使用Java 10中的 var ,同样可以像以前一样做,但源代码略少。并且能够做与以前相同的事情,但使用较少的样板代码正是 var 的关键,无论你是否使用交叉类型。

So the possibility to do the same using var in Java 10 allows, well, to do the same as before, but with slightly less source code. And being able to do the same things as before but with less boilerplate code is exactly what var is about, whether you use intersection types or not.

这篇关于使用局部类型推断的交叉点类型的有用应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆