https://kotlinlang.org logo
Docs
Join the conversationJoin Slack
Channels
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
alexa
algeria
algolialibraries
amsterdam
android
android-architecture
android-databinding
android-studio
androidgithubprojects
androidthings
androidx
androidx-xprocessing
anime
anko
announcements
apollo-kotlin
appintro
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chicago
chile
china
chucker
cincinnati-user-group
cli
clikt
cloudfoundry
cn
cobalt
code-coverage
codeforces
codemash-precompiler
codereview
codingame
codingconventions
coimbatore
collaborations
colombia
colorado
communities
competitive-programming
competitivecoding
compiler
compose
compose-android
compose-desktop
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effective-kotlin
effectivekotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
flow
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
functional
funktionale
gamedev
ge-kotlin
general-advice
georgia
geospatial
german-lang
getting-started
github-workflows-kt
glance
godot-kotlin
google-io
gradle
graphic
graphkool
graphql
graphql-kotlin
graviton-browser
greece
grpc
gsoc
gui
hackathons
hacktoberfest
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
jackson-kotlin
jadx
japanese
jasync-sql
java-to-kotlin-refactoring
javadevelopers
javafx
javalin
javascript
jdbi
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm-ir-backend-feedback
jxadapter
k2-early-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kinta
klaxon
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-dev
komapper
kondor-json
kong
kontent
kontributors
korau
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlin-asia
kotlin-beam
kotlin-by-example
kotlin-csv
kotlin-data-storage
kotlin-foundation
kotlin-fuel
kotlin-in-action
kotlin-inject
kotlin-latam
kotlin-logging
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlin-szeged
kotlin-website
kotlinacademy
kotlinbot
kotlinconf
kotlindl
kotlinforbeginners
kotlingforbeginners
kotlinlondon
kotlinmad
kotlinprogrammers
kotlinsu
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlinx-datetime
kotlinx-files
kotlinx-html
kotrix
kotson
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
ktcc
ktfmt
ktlint
ktor
ktp
kubed
kug-leads
kug-torino
kvision
kweb
lambdaworld_cadiz
lanark
language-evolution
language-proposals
latvia
leakcanary
leedskotlinusergroup
lets-have-fun
libgdx
libkgd
library-development
linkeddata
lithuania
london
losangeles
lottie
love
lychee
macedonia
machinelearningbawas
madrid
malaysia
mathematics
meetkotlin
memes
meta
metro-detroit
mexico
miami
micronaut
minnesota
minutest
mirror
mockk
moko
moldova
monsterpuzzle
montreal
moonbean
morocco
motionlayout
mpapt
mu
multiplatform
mumbai
munich
mvikotlin
mvrx
myndocs-oauth2-server
naming
navigation-architecture-component
nepal
new-mexico
new-zealand
newname
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
oolong
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
practical-functional-programming
proguard
prozis-android-backup
pyhsikal
python
python-contributors
quasar
random
re
react
reaktive
realm
realworldkotlin
reductor
reduks
redux
redux-kotlin
refactoring-to-kotlin
reflect
refreshversions
reports
result
rethink
revolver
rhein-main
rocksdb
romania
room
rpi-pico
rsocket
russian
russian_feed
russian-kotlinasfirst
rx
rxjava
san-diego
science
scotland
scrcast
scrimage
script
scripting
seattle
serialization
server
sg-user-group
singapore
skia-wasm-interop-temp
skrape-it
slovak
snake
sofl-user-group
southafrica
spacemacs
spain
spanish
speaking
spek
spin
splitties
spotify-mobius
spring
spring-security
squarelibraries
stackoverflow
stacks
stayhungrystayfoolish
stdlib
stlouis
strife-discord-lib
strikt
students
stuttgart
sudan
swagger-gradle-codegen
swarm
sweden
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
test
testing
testtestest
texas
tgbotapi
thailand
tornadofx
touchlab-tools
training
tricity-kotlin-user-group
trójmiasto
truth
tunisia
turkey
turkiye
twitter-feed
uae
udacityindia
uk
ukrainian
uniflow
unkonf
uruguay
utah
uuid
vancouver
vankotlin
vertx
videos
vienna
vietnam
vim
vkug
vuejs
web-mpp
webassembly
webrtc
wimix_sentry
wwdc
zircon
Powered by Linen
javascript
  • j

    julien lengrand-lambert

    03/30/2022, 2:14 PM
    Hey folks, I'm rather new to Kotlin JS, trying to import
    async
    functions into Kotlin, some pointers would be greatly appreciated because I'm early missing something (https://stackoverflow.com/questions/71678834/how-do-i-import-and-use-an-async-js-function-in-kotlin-js)
    s
    b
    j
    • 4
    • 14
  • j

    julien lengrand-lambert

    03/30/2022, 9:31 PM
    I have a question regarding a Kotlin JS snippet. It look like my nullable variables become undefined when being used inside my component
    data class FirebaseUser(
        val email: String,
        val uid: String,
        val accessToken: String,
    )
    
    @JsModule("@jlengrand/firebase-ports")
    @JsNonModule
    external object FirebasePorts{
        fun logIn() : Promise<FirebaseUser>
    }                
    
    var user : FirebaseUser? by mutableStateOf(null)
    
    Button(attrs = {
                        onClick {
                            console.log(JSON.stringify(user))                        
                            console.log(user)
                            console.log(user!!.uid)
                        }
                    }) {
    When doing this, ths results are as following :
    {"accessToken":"exampleToken","email":"<mailto:example@gmail.com|example@gmail.com>","uid":"example"}
    {accessToken:exampleToken,email:example@gmail.com,uid:example}
    undefined
    Is that expected, and how do I fix this? I mean, the value is there clearly
    t
    b
    • 3
    • 6
  • j

    julien lengrand-lambert

    03/31/2022, 8:18 AM
    One more newbie question 🙂. I have defined a List in the external interface. Except it doesn't behave like a kotlin list as I'm hitting a lot of
    Uncaught TypeError: ensureNotNull(...).iterator_0_k$ is not a function
    errors (same for `ìsEmpty`and any other idiomatic List function).
    external interface FirestoreMessage{
        val id: String
        val content: String
    }
    
    @JsModule("@jlengrand/firebase-ports")
    @JsNonModule
    external object FirebasePorts{
        fun logIn() : Promise<FirebaseUser>
        fun logOut()
    
        fun saveMessage(uid: String, message: String)
        fun getMessages(uid: String) : Promise<List<FirestoreMessage>>
    }
    Do you have a reference on how to use lists in external interfaces by any chance?
    b
    g
    t
    • 4
    • 6
  • j

    julien lengrand-lambert

    03/31/2022, 8:18 AM
    Damn I like Kotlin Js but the amount of resources available is light at the moment 😄. Luckily folks in this slack are super useful
    ☝️ 1
    • 1
    • 1
  • a

    andylamax

    04/01/2022, 12:01 AM
    I have a couple of question to the kotlin team 1. Is there a reason why the Kotlin
    Long
    object is not mapped to Javascript's
    BigInt
    ? 2. Is there a reason why Kotlin
    Number
    is not mapped to Javascript's
    Number
    3. Is there a reason why Kotlin
    Map
    and
    Set
    are not mapped to Javascript's
    Map
    and
    Set
    respectively?
    j
    e
    +2
    • 5
    • 14
  • j

    julien lengrand-lambert

    04/01/2022, 1:39 PM
    Hey folks, Do you know where I can find an example on how to map Javascript listeners to a Kotlin JS app ? I am specifically looking at https://firebase.google.com/docs/firestore/query-data/listen#web-version-9.
    import { doc, onSnapshot } from "firebase/firestore";
    
    const unsub = onSnapshot(doc(db, "cities", "SF"), (doc) => {
        console.log("Current data: ", doc.data());
    });
    This snippet listens to realtime changes in firestore and triggers the callback function then. I literally have no clear idea how to bind this with my Kotlin. The main issue I see is that I would need to pass a function as input to the binding, with access to the kotlin side data 🧐
    d
    • 2
    • 7
  • g

    grahamborland

    04/01/2022, 3:01 PM
    Another beginners’ question about
    Long
    and
    Number
    . I have this Kotlin code:
    @JsExport
    fun isNegative(amount: Long) : Boolean = amount < 0L
    which fails at runtime in Typescript because
    TypeError: amount.compareTo_n4fqi2_k$ is not a function
    Can someone gently guide me towards what kind of solutions I should be investigating? Should I just not use
    Long
    in the Kotlin code, or should I be adding some conversion logic somewhere?
    e
    b
    • 3
    • 13
  • a

    Ayfri

    04/01/2022, 5:29 PM
    Hi ! Is it possible to set ES12 as compilation target ?
    b
    t
    • 3
    • 8
  • m

    Michael Friend

    04/01/2022, 7:28 PM
    Discovered an issue introduced in 1.6.20-M1, anyone else run into this yet? Wanted to makes sure it wasn’t a duplicate https://youtrack.jetbrains.com/issue/KT-51802
    k
    j
    b
    • 4
    • 11
  • g

    Gopal S Akshintala

    04/03/2022, 1:03 PM
    Hi, can someone please help me (if possible with any sample references), how to execute Javascript from Kotlin? I googled around few solutions like CashApp/Zipline and Mozilla/Rhino but am struggling to wrap my head around them. I feel I can learn quickly from a working code. Thanks!
    r
    • 2
    • 3
  • a

    Akram Bensalem

    04/03/2022, 4:35 PM
    Hello I'm trying to custom navigation for Compose web I use Decompose and it works fine but I want to update the url in the same time I always get this error It seems that the server try to find the main .js file for the specific location!! which is not what I want because there is no such files!!! Anyone here know a trick to disable the server from doing that ?
    t
    • 2
    • 3
  • l

    Luc Girardin

    04/04/2022, 10:54 AM
    For now quite some time, I am no longer able to build my JavaScript targets using dependency substitutions applied to composite builds (either include or includeBuild). The main benefit was that one could skip the publishToMavenLocal step and therefore boost productivity. This works nicely for other targets, but not for JS. I have tried to get attention by filling an issue and creating a sample project (https://youtrack.jetbrains.com/issue/KT-50064), but alas without much success as Kotlin 1.6.20 still exhibits the same problem. I am therefore wondering if any of you has found a good setup where one doesn’t need to resort to creating artifacts during the development cycles but still eventually be able to publish these artifacts once stable.
    a
    • 2
    • 4
  • b

    bashor

    04/04/2022, 1:29 PM
    We are eager to receive your feedback! https://twitter.com/bashorov/status/1510971584458235905
    🎉 6
    🚀 4
    :kotlin-intensifies: 9
    ❤️ 7
    r
    • 2
    • 2
  • a

    andylamax

    04/04/2022, 9:00 PM
    Anyone else getting
    Task :jsBrowserTest
    java.lang.IllegalStateException: command '/home/runner/.gradle/nodejs/node-v16.13.0-linux-x64/bin/node' exited with errors (exit code: 134)
    After bumping to 1.6.20? I am getting this on CI and my machine as well
    t
    r
    • 3
    • 14
  • m

    Michal Klimczak

    04/06/2022, 7:59 PM
    I'm having hard time trying to make a generic deserializing work.
    private suspend inline fun <reified T> fetch(
        url: String,
        state: ObservableValue<Collection<T>>
    ) {
        val response1 = client.get(url).body<List<T>>(typeInfo<List<T>>())
        val response2 : List<T> = client.get(url).body()
        val type = typeOf<T>()
    }
    neither response1, nor response2 is able to properly derive the generic type, even though it's reified.
    TypeInfo(type=class List, reifiedType=[object Object], kotlinType=null)
    And calling typeOf fails with a weird " This marker function should never been called. Looks like compiler did not eliminate it properly. Please, report an issue if you caught this exception." When the type is provided directly, everything works fine, obviously (
    kotlinType
    is properly defined). Is that not possible at all, even with reified type? Can I create a
    KType
    for
    List<T>
    ? Kotlin 1.6.10
    a
    • 2
    • 7
  • s

    shaktiman_droid

    04/07/2022, 4:13 PM
    With interface support in
    1.6.20
    , in the generated typescript file, I noticed the addition of
    __DoNotUserIt
    of type
    __doNotImplementIt
    Does anyone know reason behind it? It creates an issue if we have to implement that interface on
    TypeScript
    app side. Kotlin Code
    @JsExport
    interface GreetingInterface {
        val platform: String
        fun greeting(): String
    }
    Generated
    .d.ts
    file
    declare const __doNotImplementIt: unique symbol
    type __doNotImplementIt = typeof __doNotImplementIt
    
    export namespace <PACKAGE> {
        interface GreetingInterface {
            readonly platform: string;
            greeting(): string;
            readonly __doNotUseIt: __doNotImplementIt; <----- What and why is this here?
        }
    }
    TypeScript App Usage
    (example.ts)
    class Greeting implements GreetingInterface {
      platform: string = "TypeScript"
      greeting(): string {
        return "this is greeting from " + this.platform;
      }
      __doNotUseIt: typeof sdk.__doNotImplementIt; <----- What to do here apart from adding `!` so compiler doesn't complain
    }
    👀 3
    b
    a
    m
    • 4
    • 11
  • m

    Marc Knaup

    04/09/2022, 8:16 PM
    Since Kotlin 1.6.20
    fun main()
    in modules compiled with
    -Xir-per-module
    are no longer executed automatically when the module is loaded. How can I make that work again?
    t
    b
    +4
    • 7
    • 17
  • m

    Marc Knaup

    04/10/2022, 10:10 AM
    Does anyone have any idea what this is trying to tell me? Why is it loading source maps?
    r
    t
    • 3
    • 10
  • r

    Reuben F

    04/10/2022, 6:54 PM
    Hello, I am trying to bind absurd-sql (https://github.com/jlongster/absurd-sql - scroll down to "then in index.worker.js do this"). I'll attach my bindings to this thread. I'm running into an error when I try to create IndexedDBBackend: " TypeError: Class constructor k cannot be invoked without 'new'". Any ideas?
    t
    • 2
    • 13
  • j

    Julius

    04/10/2022, 10:52 PM
    Hey 🙂 I was wondering if ktor server running on nodejs is possible/supported? I found this doc about ktor server on native, but I cannot find anything about running ktor server on javascript. I want to do this because of some specific javascript dependencies
    v
    b
    • 3
    • 3
  • s

    spierce7

    04/14/2022, 4:18 PM
    Are there any benchmark of Kotlin js? i.e. I’d love to know how Kotlin stacks up against GWT or just standard written JS code.
    k
    o
    a
    • 4
    • 8
  • d

    Derek Wong

    04/19/2022, 8:10 PM
    Finally got around to upgrading to 1.6.20 Took a little bit to fix some of the JsExports, but completely worth it for interface and enum support. Also tried out the “kotlin.incremental.js.ir=true” flag, and it did seem to cut build times in half. Decided not to use it because source maps were not generating properly, but still super excited to see effort being made on this front. Thank you so much, these improvements really hit the hammer on the nail when it comes to improving developer experience. Keep up the great work ❤️
    ➕ 5
    :tnx: 2
    b
    a
    • 3
    • 6
  • h

    Hakon Grotte

    04/20/2022, 6:36 AM
    Hey guys, I’m trying to use the lodash/debounce function in my KotlinJS app. More information in thread 🙏
    👀 1
    ✔️ 1
    b
    r
    t
    • 4
    • 14
  • m

    Moritz Hofmeister

    04/21/2022, 12:58 PM
    For anyone migrating from the old kotlin wrappers (old = before pre.282 release) and to the new IR compiler: We migrated all our web projects in the last months and are now happier than ever with our project setup 🙂 (Except not having migrated to functional components yet) It took us quite some time to fully migrate our projects due to the lack of documentation and very few “big” open source projects using this stack. Therefore I created a migration guide which should hopefully enable other projects to get the migration done in a short(er) period of time. One of our projects, CampusQR, is open source. Feel free to use it as a resource when doing the migration!
    👍🏻 2
    🎉 10
    👍 5
    t
    • 2
    • 1
  • a

    Ayfri

    04/21/2022, 1:54 PM
    Hi, I'm trying to load a project using multiple gradle modules, but each submodules always get the error
    Task 'wrapper' not found in project ':packages:my-submodule'.
    , I have
    tasks.wrapper {
    	gradleVersion = "7.4.2"
    }
    In my root
    build.gradle.kts
    . I also configured my modules to uses wrapper from the
    wrapper
    task (image)
    v
    • 2
    • 2
  • a

    ansman

    04/21/2022, 3:57 PM
    I’m very excited for 1.6.20 for the JS improvements, unfortunately most of my tests broke due to the generated JS code being broken. It seems to be because
    Collection.size
    isn’t defined at runtime and calls to it returns
    undefined
    which in turn causes most things that uses collections to fail. I’m guessing it will be very hard for me to have a reproducer since this can’t possibly happen in most cases or the tests for the compiler would have caught them. Does this sound familiar to anyone else?
    😨 2
    l
    k
    m
    • 4
    • 22
  • b

    bod

    04/21/2022, 4:31 PM
    Hello, World! I've been importing node libraries and using them successfully, but for this one (express) I'm trying to use and am hitting something I don't understand. I've added this dependency:
    implementation(npm("express", "4.17.3"))
    And declared this external:
    @file:JsModule("express")
    @file:JsNonModule
    
    package express
    
    external fun express(): dynamic
    But calling
    express()
    in my code gives me:
    TypeError: express_0 is not a function
    Any idea why it's named
    express_0
    in the generated js? 🤔
    t
    a
    • 3
    • 16
  • d

    Derek Wong

    04/21/2022, 8:53 PM
    I noticed that in 1.6.20 the generated typescript definitions explicitly use “any” for types that are not exported:
    get created(): any/* kotlinx.datetime.Instant */;
    In previous versions I believe these would use undefined named types like this:
    get created(): kotlinx.datetime.Instant
    The issue with the explicit “any” type is that I’m no longer able to use my own supplemental typescript definitions for Webstorm to pick up like this:
    export namespace kotlinx.datetime {
     export class Instant {
      toDate(): Date
       __proto__: any
     }
    }
    I’m sure there is a good reason for switching over to the “any” type for unexported types, but is there any possibility of a flag to generate the named unknown types we had before? Being able to use supplemental typings is still pretty handy since a lot of the kotlin libraries are still not exportable. Also open to any alternatives to the approach I was using to add typings that works with the new export format if anyone knows.
    h
    • 2
    • 1
  • m

    mike.holler

    04/21/2022, 9:51 PM
    How would you all create
    external
    declarations for the following signatures?
    flatbuffers.Builder = function(opt_initial_size) { ... }
    flatbuffers.Builder.prototype.clear = function() { ... }
    What I have tried is:
    @file:JsModule("flatbuffers")
    @file:JsNonModule
    package flatbuffers
    
    external class Builder(initialSize: Int) {
        fun clear()
    }
    But I get an error:
    TypeError: Builder is not a constructor
    t
    b
    • 3
    • 23
  • b

    bod

    04/22/2022, 6:25 AM
    Hi again! So, I'm using a library that expects me to return an
    AsyncIterator
    . For instance here's something in JS :
    myAsyncIterator = async function* () {
            for await (const word of ["one", "two", "three"]) {
              yield { count: word };
            }
          }
    Any idea how to write an equivalent in Kotlin?
    t
    s
    • 3
    • 21
Powered by Linen
Title
b

bod

04/22/2022, 6:25 AM
Hi again! So, I'm using a library that expects me to return an
AsyncIterator
. For instance here's something in JS :
myAsyncIterator = async function* () {
        for await (const word of ["one", "two", "three"]) {
          yield { count: word };
        }
      }
Any idea how to write an equivalent in Kotlin?
t

turansky

04/22/2022, 11:57 AM
You can check
AsyncIterator
contract in
lib.dom.d.ts
to write effective addapter
b

bod

04/22/2022, 12:36 PM
Thanks! I can't seem to find it there 🤔
but I'm especially wondering how one can write the equivalent of an "function*" (a generator function) in Kotlin
and an "async" one at that
t

turansky

04/22/2022, 10:39 PM
I can’t seem to find it there 🤔
Do you use IDEA?
And which compiler do you use?
b

bod

04/23/2022, 8:06 AM
Yes IDEA, and the IR one
t

turansky

04/23/2022, 7:00 PM
It’s from IDEA typings
b

bod

04/23/2022, 7:05 PM
Very interesting! I wonder why I can't see this but I'll investigate. Thanks a lot!
t

turansky

04/23/2022, 7:14 PM
https://github.com/JetBrains/kotlin-wrappers/pull/1456
Very interesting! I wonder why I can’t see this but I’ll investigate
1. Create JS file 2. Write
Symbol.asyncIterator
3.
Cmd
+ click on
asyncIterator
4. PROFIT
👀 1
https://github.com/JetBrains/kotlin-wrappers/pull/1457
b

bod

04/24/2022, 12:27 PM
wow! Very cool. Let me see if I can make this work in my case
well, that helped me a lot! I finally managed to make this work. Huge thanks! 🙏
t

turansky

04/24/2022, 6:23 PM
Do you have analog of initial code?
b

bod

04/27/2022, 8:16 AM
(sorry for the late reply) You can see how I did it here.
I use a bunch of
dynamic
so it's weakly typed, but that's ok for my use-case
t

turansky

04/27/2022, 9:31 AM
You can use wrappers for strict typings
👍 1
s

Sergei Grishchenko

04/27/2022, 10:14 AM
Idiomatically JS generators (
function*
) relates to
suspend
in Kotlin but I think we (wrappers developers) need some invent some wrappers and strategies to make integration to generators more seamless, example of such integration is
public suspend fun <T> kotlin.js.Promise<T>.await(): T { /* compiled code */ }
from
kotlinx.coroutines
b

bod

04/27/2022, 12:34 PM
yeah it kinds of makes sense in the end when you know where to look at 😅 But I think I wouldn't have made it alone without the pointers from Victor. Maybe it's easier if you're a more experienced JS developer than myself.
View count: 3