如何创建接口的匿名实现? [英] How to create an anonymous implementation of an interface?

查看:334
本文介绍了如何创建接口的匿名实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个界面:

interface TileSet {
    fun contains(x: Int, y: Int) : Boolean
}

我希望能够创建图块集的并集(瓦片是一对x和y整数坐标):

I want to be able to create unions of sets of tiles (tile is a pair of x and y integer coordinates):

fun TileSet.union(another: TileSet) : TileSet = 
   // ..

在Java 8中,我可以这样做:

In Java 8, I could do it like this:

@FunctionalInterface
public interface TileSet {
    boolean contains(int x, int y);

    public default TileSet unite(TileSet another) {
        return (x, y) -> TileSet.this.contains(x, y) && another.contains(x, y);
    }
}

因此在TileSet#unite()中使用lambda实现了接口.或者可以使用旧的匿名类方法来实现:

So an interface is implemented with a lambda in TileSet#unite(). Or it could be implemented with the old anonymous class approach:

public default TileSet unite(TileSet another) {
    return new TileSet() {
         @Override
         public boolean contains(int x, int y) {
             return TileSet.this.contains(x, y) && another.contains(x, y);
         }
    }
}

如何在Kotlin中创建单方法接口的匿名实现?

How can I create an anonymous implementation of a single-method interface in Kotlin?

如果使用(Int, Int) -> Boolean而不是TileSet,我知道该怎么做,但是我希望该类型具有描述性名称,而不仅仅是功能签名.

I know how to do it if I use (Int, Int) -> Boolean instead of TileSet, but I want the type to have a descriptive name rather than just a function signature.

推荐答案

文档(用于匿名类,但不用于接口).

There are examples in the documentation for anonymous classes, but not for interfaces.

这是我创建接口实例的方式:

This is how I created an instance of an interface:

fun TileSet.union(another: TileSet) : TileSet =
    object : TileSet {
        override fun contains(x: Int, y: Int) : Boolean =
            this@union.contains(x, y) || another.contains(x, y)
    }

请注意,与文档中的示例不同,在object : TileSet之后没有括号.

Notice that, unlike in the example from documentation, there are no parentheses after object : TileSet.

这篇关于如何创建接口的匿名实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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