1

I have a js interop function which is using the for in construct to iterate over the input elements, but it's throwing error at runtime.

native("document")
val ndoc: dynamic = noImpl

fun jsInterOp() {
    js("console.log('JS inling from kotlin')")

    val ies = ndoc.getElementsByTagName("input")
    for (e in ies) {
      console.log("Input element ID: ${e.id}")
    } 
}

Getting the following js error

Uncaught TypeError: r.iterator is not a functionKotlin.defineRootPackage.kotlin.Kotlin.definePackage.js.Kotlin.definePackage.iterator_s8jyvl$ @ kotlin.js:2538

Any suggestions on how to fix this one?

Kotlin : M12

The generated js code for the function is,

    jsInterOp: function () {
      var tmp$0;
      console.log('JS inling from kotlin');
      var ies = document.getElementsByTagName('input');
      tmp$0 = Kotlin.modules['stdlib'].kotlin.js.iterator_s8jyvl$(ies);
      while (tmp$0.hasNext()) {
        var e = tmp$0.next();
        console.log('Input element ID: ' + e.id);
      }
    },
1
  • Could you show the corresponding peace of the generated JS? Commented Jun 20, 2015 at 18:38

2 Answers 2

3

forEach didn't work because it's an Array function in JS, but getElementsByTagName returns HTMLCollection . So i changed the kotlin code to use the traditional for loop which iterate over this collection and is work as expected.

 val ies = ndoc.getElementsByTagName("input")
 for (i in 0..(ies.length as Int) - 1) {
    console.log("InputElement-${i} : ${ies[i].id}")
 }
Sign up to request clarification or add additional context in comments.

3 Comments

Note that Kotlin's for in is not the same as JavaScript's for in and they have the different semantic.
@bashor could you please provide more details or any doc explaining how it's semantically different in JS ?
And about JS for-in
0

Kotlin for-loop uses a lot of internal magic.forEach() is more straightforward on JS. Try this:

ies.iterator().forEach { ... }

It seems to be a bug in Kotlin M12, because I was unable to do a for-loop even on simple a list.

for(i in listOf(1, 2));  // TranslationInternalException

Also

I am not sure what is that document that you use here, but you may like the standard API:

import kotlin.browser.document
val ies = document.getElementsByTagName("input")

2 Comments

Thanks! native("document") is used just to learn how js interop works in kotlin.
ies.iterator().forEach { ... } doesn't work, getting the same error Uncaught TypeError: r.iterator is not a function . More over, now it's giving a warning message to use sequence() function instead of iterator().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.