About invoking JS from Kotlin. Taking the example ...
# javascript
v
About invoking JS from Kotlin. Taking the example of String.prototype.charCodeAt(index). Is there a way to invoke directly from Kotlin without
js()
, avoiding the
dynamic
type? For example:
Copy code
val sentence = "The quick brown fox jumps over the lazy dog"
val index = 4
val charCode = js("sentence.charCodeAt($index)")
// charCode = 113
1
p
can you use API provided by Kotlin for the string? I think the equivalent is String.codePointAt
ah, sorry - it’s available only for the JVM
v
Yeah 😞 I was just asking in general, I guess a lot of the Kotlin stdlib isn't implemented in Kotlin/JS and Kotlin/Common yet. I wonder if adding this kind of functions is something wanted by the Kotlin team. I'd be happy to raise PRs with this.
👍 1
p
sticking to this particular example for a while, you can achieve what you need with
sentence[index].code
❤️ 1
v
Oh yeah! I guess
String.codePointAt
is just the Kotlin/JVM sugar layer. And
Char.code
is the Kotlin way of doing things. A
@see [Char.code]
in the docs of
codePointAt
would be awesome 🙂. But I guess if Java changes the
codePointAt
, this documentation would be broken
👍 1
Thanks @Piotr Krzemiński.
👌 1
b
Alternatively you can declare your own typesafe global api bindings
v
I'm doing something like that. Multiplatform "String to UTF16BE Byte Array". Super straightforward in iOS, Android and JVM. But inside the JS function, the dynamic appeared and I was trying to go around it. So this question came, if there was another way of doing it, or doing something like @Big Chungus suggested. Good that for this specific case there's indeed a work-around. But I guess now I know how to proceed in the future. Thanks everyone
💪 1
p
for completeness, the JS API binding would look like this:
Copy code
@Suppress("NOTHING_TO_INLINE")
inline fun String.charCodeAt(index: Int): Int = asDynamic().charCodeAt(index) as Int

val sentence = "The quick brown fox jumps over the lazy dog"
val index = 3
val charCode = sentence.charCodeAt(index)
maybe it’s possible to do it in a more idiomatic/less noisy way, but this works ☝️
👍 1
b
That's not API binding.
I meant external declarations. Although both work.
p
Screenshot 2022-11-18 at 12.30.57.png
b
Yes, you cannot mix externals and extensions