Hi,
I tried the “Generic functions” sample from http://confluence.jetbrains.net/display/Kotlin/Functions like this:
``
fun main(args : Array<String>) {
println(singletonArray(1001))
}
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?
Thanks,
Zemian
Yes, outdated doc. Corrected, thanks.
Now this example reads:
``
fun singletonArray<T>(item : T) : Array<T> {
return Array<T>(1, {item})
}
Almost.
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)
Bug?
Andrey, one more question. Looking at the API doc at http://jetbrains.github.com/kotlin/versions/snapshot/apidocs/index.html
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: http://youtrack.jetbrains.com/issue/KT-3050
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:
https://github.com/JetBrains/kotlin/blob/master/compiler/frontend/src/jet/Arrays.jet