Should this work without including <SomeInterfa...
# announcements
s
Should this work without including <SomeInterface> ?
Copy code
interface SomeInterface
enum class SomeEnum: SomeInterface { ValueA, ValueB }

fun someFun(array: Array<SomeInterface>) {}

fun calls() {
	val val1 = arrayOf<SomeInterface>(SomeEnum.ValueA, SomeEnum.ValueB) // Array<SomeInterface>
	val val2 = arrayOf(SomeEnum.ValueA, SomeEnum.ValueB) // Array<SomeEnum>
	val val3 = SomeEnum.values() // Array<SomeEnum>
	val val4 = SomeEnum.values() as Array<SomeInterface> // Array<SomeInterface>
	
	someFun(arrayOf(SomeEnum.ValueA, SomeEnum.ValueB)) // Works
	someFun(SomeEnum.values()) // Compiler error
	
	someFun(val1) // Works
	someFun(val2) // Compiler error
	someFun(val3) // Compiler error
	someFun(val4) // Works
}
s
you might want to use lists instead
arrays have a
.toList()
extension method which helps a lot
s
Thanks. I am trying to detect if this is intended behaviour or not for Array.
s
I’m pretty sure it is - looking a bit more closely at the code, the declaration for Kotlin arrays is just
public class Array<T>
, which means
T
is invariant
see: http://kotlinlang.org/docs/reference/basic-types.html#arrays
Note: unlike Java, arrays in Kotlin are invariant. This means that Kotlin does not let us assign an
Array<String>
to an
Array<Any>
, which prevents a possible runtime failure (but you can use
Array<out Any>
, see Type Projections).
it looks like technically you can just redefine
someFun()
to accept
Array<out SomeInterface>
but I imagine you do so at your own risk
s
Thanks, I did not know that.