El uso de la nueva función de inferencia de constructor en Kotlin permite que el tipo de constructor se realice por uso, en lugar de una declaración más explícita.
Por ejemplo
class Test<T> { fun add(a: T) {} fun secondFun(a: T) {} fun <T> Test<T>.lambda(a: (T) -> Unit) {} } @OptIn(ExperimentalTypeInference::class) fun <T> builder(@BuilderInference x: Test<T>.() -> Unit): Test<T> { return Test<T>().apply(x) } El siguiente código da como resultado un constructor con un tipo Int como T .
val x = builder { add(1) } // has type Test<Int> Sin embargo, el uso del tipo en llamadas posteriores después de la add inicial genera ambigüedad en el compilador de kotlin.
val x: Test<Int> = builder { add(1) lambda { it + 1 } } Esto falla en el uso del + con
Overload resolution ambiguity: public operator fun <T> Array<TypeVariable(T)>.plus(element: TypeVariable(T)): Array<TypeVariable(T)> defined in kotlin.collections public operator fun ByteArray.plus(element: Byte): ByteArray defined in kotlin.collections public operator fun IntArray.plus(element: Int): IntArray defined in kotlin.collections public operator fun LongArray.plus(element: Long): LongArray defined in kotlin.collections public operator fun ShortArray.plus(element: Short): ShortArray defined in kotlin.collections public operator fun String?.plus(other: Any?): String defined in kotlin public inline operator fun UByteArray.plus(element: UByte): UByteArray defined in kotlin.collections public inline operator fun UIntArray.plus(element: UInt): UIntArray defined in kotlin.collections public inline operator fun ULongArray.plus(element: ULong): ULongArray defined in kotlin.collections public inline operator fun UShortArray.plus(element: UShort): UShortArray defined in kotlin.collections public operator fun <T> Collection<TypeVariable(T)>.plus(element: TypeVariable(T)): List<TypeVariable(T)> defined in kotlin.collections public operator fun <T> Iterable<TypeVariable(T)>.plus(element: TypeVariable(T)): List<TypeVariable(T)> defined in kotlin.collections public operator fun <T> Set<TypeVariable(T)>.plus(element: TypeVariable(T)): Set<TypeVariable(T)> defined in kotlin.collections public operator fun <T> Sequence<TypeVariable(T)>.plus(element: TypeVariable(T)): Sequence<TypeVariable(T)> defined in kotlin.sequences Aparentemente, no continúa con la idea de que el tipo T es un int . Aunque IntelliJ tiene la sugerencia de tipo Int en su propio análisis dentro it la lambda.
¿Hay alguna manera de llamar al método lambda DSL con la resolución de Int sin necesidad de tipeo explícito dado que ya ha habido una llamada que puede inferir un tipo? ¿O es esta una limitación de Builder Inference en kotlin, ya que potencialmente está buscando un tipo más específico/general en usos futuros de T .