如何在Kotlin中将vararg传递给varag函数或构造函数? [英] How to Pass vararg to a varag function or constructor in Kotlin?
本文介绍了如何在Kotlin中将vararg传递给varag函数或构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Kotlin不允许我的子类将vararg传递给我的超类构造函数 这是我的Operation课:
Kotlin does not allow my subclass to pass vararg to my super class constuctor Here is my Operation class:
package br.com.xp.operation
import java.util.ArrayList
abstract class Operation(vararg values: Value) : Value {
protected var values: MutableList<Value> = ArrayList()
internal abstract val operator: String
}
这是我的SubtractionOperation类:
and here is my SubtractionOperation class:
package br.com.xp.operation
class SubtractionOperation private constructor(vararg values: Value) : Operation(values) {
override val operator: String
get() = "-"
}
编译说:
类型不匹配找到所需值数组
Type mismatch Required Value found Array
任何人都可以解释为什么这不可能吗?
Can anyone explain why this is not possible?
推荐答案
来自文档:
在函数中,类型为
T
的vararg
-参数作为T
的数组可见.
Inside a function a
vararg
-parameter of typeT
is visible as an array ofT
.
因此,在SubtractionOperation
构造函数中,values
实际上是Array<Value>
.您需要使用 spread 运算符(*
)来转发这些消息:
So in the SubtractionOperation
constructor, values
is really an Array<Value>
. You need to use the spread operator (*
) to forward these on:
class SubtractionOperation private constructor(vararg values: Value) : Operation(*values) ...
这篇关于如何在Kotlin中将vararg传递给varag函数或构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文