Skip to content

Variance for function output types is ignored #1933

Open
@DanySK

Description

@DanySK

Describe the bug

Generating this function is impossible:

fun <T> foo(): Array<out T> = TODO()

Note that this prevents an entire family of functions from being generated

To Reproduce

Run this:

fun main(args: Array<String>) {
    val funspec = FunSpec.builder("foo")
        .addTypeVariable(TypeVariableName("T"))
        .returns(
            ClassName.bestGuess("kotlin.Array")
                .parameterizedBy(TypeVariableName("T", variance = KModifier.OUT))
        )
        .addStatement("TODO()")
        .build()
    println(
        FileSpec.builder("foo.bar", "Baz")
        .addFunction(funspec)
        .build()
        .toString()
    )
}

Expected:

package foo.bar

import kotlin.Array

public fun <T> foo(): Array<out T> {
  TODO()
}

actual:

package foo.bar

import kotlin.Array

public fun <T> foo(): Array<T> {
  TODO()
}

Expected behavior
See above

Additional context
Stumbled on this while building a code generator that wraps fun Array<out T>?.orEmpty(): Array<out T>.
I can only generate: fun <reified T, ID : Any> Field<ID, Array<T>?>.orEmpty(): Array<T>, but I need fun <reified T, ID : Any> Field<ID, Array<T>?>.orEmpty(): Array<out T> for the compilation to succeed.

Alternatively (but it is a workaround) it should be allowed to omit the return type and let the compiler infer (in my case, fun <reified T, ID : Any> Field<ID, Array<T>?>.orEmpty() = ... would work

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions