A的Kotlin变量到B的变量 [英] Kotlin vararg of A to vararg of B

查看:95
本文介绍了A的Kotlin变量到B的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个可由其他Filter类组成的Filter类,目标是每个过滤器都可以处理一个对象并返回一个布尔值,如果它是由多个过滤器组成的,则它将计算其所有对象的AND过滤器.

I am trying to implement a Filter class that can be composed of other Filter classes.The goal is that each filter can process an object and return a boolean, and if it is made of several filters it computes the AND of all its filters.

我正在尝试让构造函数之一采用谓词的 vararg ,该谓词需要转换为Filters的 vararg .编译器说,这些参数都不能调用任何函数(主要构造函数和第一构造函数).

I am trying to get one of the constructors to take a vararg of predicates, which needs to be converted into a vararg of Filters. The compiler says that none of the functions (the primary and first secondary constructors) can be called with these parameters.

我的理解是*应该将List<Filter<T>>转换为vararg Filter<T>,但不能正常工作.

My understanding is that * should convert List<Filter<T>> into vararg Filter<T>, but it is not working.

class Filter<in T>(private vararg val filters: Filter<T>) {
    constructor(predicate: (T) -> Boolean) : this(Filter(predicate))
    constructor(vararg predicates: (T) -> Boolean) : this(Filter<T>(*(predicates.map { predicate -> Filter<T>(predicate) })))

    fun process(input: T): Boolean {
        for (filter in filters) { if (!filter.process(input)) return false }
        return true
    }
}

我该怎么做?

此外,与仅检查谓词相比,遍历仅一个谓词的过滤器是否会产生较大的开销(考虑到过滤一个列表,这将被称为很多次)?

Also, is it a big overhead iterating over filters of just one predicate compared to just checking the predicate (considering this will be called a lot of times, to filter a list)?

推荐答案

没有'*'是扩展运算符,可以在数组上使用以作为vararg参数传递.您需要将最后一个构造函数更改为:

No '*' is the spread opperator and can be used on array to be passed as vararg parameter. You will need to change your last constructor to:

constructor(vararg predicates: (T) -> Boolean) : this(*predicates.map { Filter(it) }.toTypedArray())

谓词映射到Filter列表,然后将该列表转换为数组,并使用传播运算符将其作为vararg传递.

predicates is map to a list of Filter and then the list is converted to an array and passed as vararg using the spread operator.

请注意,您不需要指定任何类型,因为编译器可以推断出这些类型.

Note that you don't need to specify any type because the compiler can infer thoses types.

这篇关于A的Kotlin变量到B的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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