1

Having a java class, using androidStudio to translate to kotlin. Got a error and not sure how to correctly translate it.

The java code:

public class BaseDataImpl extends BaseData {

    private final BaseData[] translators;

    public BaseDataImpl(final BaseData... translators) {
        this.translators = cloneArray(translators);
    }

    public static <T> T[] cloneArray(final T[] array) {
        if (array == null) {
            return null;
        }
        return array.clone();
    }

}

after the code translation, got error: required Array<BaseData>?, found Array<out BaseData>, but the translators in the cloneArray<BaseData>(translators) call is defined as val translators: Array<BaseData>?,

anyone could help to explain?

class BaseDataImpl(vararg translators: BaseData) : BaseData() {

    private val translators: Array<BaseData>?

    init {
        this.translators = cloneArray<BaseData>(translators)  //<=== error:  required Array<BaseData>?, found Array<out BaseData>
    }

    companion object {
        fun <T> cloneArray(array: Array<T>?): Array<T>? {
            return array?.clone()
        }
    }

}
lannyf
  • 9,865
  • 12
  • 70
  • 152

1 Answers1

3

It is written in the Kotlin function reference regarding varargs:

Inside a function a vararg-parameter of type T is visible as an array of T, i.e. the ts variable in the example above has type Array<out T>.

where the referenced function was:

function <T> asList(vararg ts: T): List<T>

So in your case you actually pass an Array<out BaseData> but you only accept an array of type Array<T>? (in your case Array<BaseData>). Either you adapt all of the types to Array<out T> (which basically is similar as saying List<? extends BaseData> in Java) or you take care that you are only dealing with Ts instead, e.g. with:

inline fun <reified T> cloneArray(array: Array<out T>?): Array<T>? {
        return array?.clone()?.map { it }?.toTypedArray()
}

But look up the documentation regarding this: Kotlin generics reference - type projections. You probably can accomplish this even easier.

Roland
  • 22,259
  • 4
  • 57
  • 84