Generic function is not compiling


I tried the “Generic functions” sample from like this:


fun main(args : Array<String>) {
fun singletonArray<T>(item : T) : Array<T> {
  val result = Array<T>(1)
  result[0] = item
  return result

but the compiler complains:


ERROR: /Users/zemian/apps/kotlinc/./Test.kt: (5, 24) No value passed for parameter init
exec() finished with COMPILATION_ERROR return code

Outdated doc? What’s the proper way to do generic function?


Yes, outdated doc. Corrected, thanks.

Now this example reads:


fun singletonArray<T>(item : T) : Array<T> {
  return Array<T>(1, {item})


It now compiles, but it won’t run.


Exception in thread “main” java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
     at namespace.main(Test.kt:2)


Andrey, one more question. Looking at the API doc at

where can I see the constructor signatures of Array type? Is that the jet.Array? I don’t see any constructors listed.

Sorry, I should have checked it running. It's a bug, and a rather deep one. I reported it here:

My advice would be to avoid using arrays (both in Kotlin and Java), because they are a low-level implementation mechanism, and reasonably high-leveled code should use collections.

Yes, it's jet.Array, but the constructor is not there for some reason...

Have a look here: