[M2-js]How create native array and object?


#1

var x = [1,2,3]; var x = {x:10}; ? Also, will labeled tuples be in version 1.0? If not, what can we use similar to json?


#2

You can create arrays and maps as follows; not sure if/when labelled tuples will be added.

val x = array(1, 2, 3) val y = hashMap("a" to 3, "b" to 7)


#3

I download https://github.com/abreslav/kotlin-js-hello, open it, but kotlin-jslib.jar doesn't have array and hashMap. Version 0.1.2580


#4

Ah sorry - I was talking JVM stuff; we're in the process of migrating the standard library over to JS; its going to take a few weeks to have those APIs available in JS.


#5

But, it's not about standart library. array and hashMap return JVM classes. I guese I can write something like this

native(“Array”)
class JsArray<T>() {
  fun push(item:T):Unit = js.noImpl
  fun pop() : T = js.noImpl
  fun get(index:Int):T = js.noImpl
  fun set(index : Int, value : T) : Unit = js.noImpl
}

  val x = JsArray<Int>()
  x.push(1)
  var z = x[0]

But it generate

  var x = new Array;
  x.push(1);
  var z = x.get(0);

What I need to change to get?
  var x = new Array;
  x.push(1);
  var z = x[0];


#6

There is already a kotlin standard library in JS, though its only got the basics of using kotlin code in JS so far; we're gradually migrating more of the kotlin.* APIs over to work on JS.

We have a java.util.ArrayList compatible class already in JS for example. But more work is required to get the various kotlin package APIs working along with arrays and maps.


#7

So, now there is not way to generate javascript square brackets? All I can do it's Array.prototype.get = function(x){   return this[x]; }

Object.prototype.get = function(x){
  return this[x];
}

?


#8

Hi! Kotlin arrays are directly translated to JavaScript arrays. The difference is that Kotlin arrays are immutable. Also JavaScript - backend is lacking those nice constructor functions from stdlib like array(1, 2, 3) but they will be there soon.

As for native objects there is no equivalent on language level. You can use function js.json to create json object to use it with some native library. It is not translated directly to object literal but uses some ugly wrapper functions.
Example:

val a = js.json(#(“1”, “value”), #(“2”, “value2”))
a[“3”] = "value3"
val c = a[“2”]


This example can be made prettier by introducing “to” function like this:

val a = js.json (
  “1” to “value”,
  “2” to “value2”
)

But still not as nice as the json notation.

Any suggestions are welcome.


#9

>Kotlin arrays are directly translated to JavaScript arrays. But, what if I want use native arrays, with push,pop api? http://devnet.jetbrains.net/thread/436786?tstart=0 >Any suggestions are welcome. May be add Symbols? val a = js.json (   '1 to "value",   '2 to "value2" )


#10

You can easily add the following extension functions in Kotlin JS:

fun <T> Array<T>.push(item: T) { asDynamic().push(item) }
fun <T> Array<T>.pop(): T = asDynamic().pop() as T