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
  • g

    Gunslingor

    08/12/2020, 9:07 PM
    How does one overload an external interfaces var? i.e. the value for var content can be either a string or Content type... hmmm... I guess setting it to any works, but that's not really true... its 2of not AnyOf, lol.
    external interface Block {
        var id: String
        var label: String
        var select: Boolean
        var attributes: Attributes
        var content: Content //string or jsObject
        var activate: Boolean
    }
    external interface Attributes {
        var `class`: String
    }
    external interface Content {
        var type: String
    }
    r
    • 2
    • 6
  • v

    Vampire

    08/14/2020, 9:28 AM
    I added
    @types/semver
    to my dependencies and now Dukat is super unhappy, whining with
    Cannot read property 'fileName' of undefined
    as reported at https://github.com/Kotlin/dukat/issues/365. Anyone any idea what goes wrong and how to work-around it?
    i
    • 2
    • 1
  • u

    3bdoelnaggar

    08/14/2020, 2:48 PM
    I have error including kotlinx-date-time https://github.com/Kotlin/kotlinx-datetime/issues/35
    :youtrack: 1
    i
    • 2
    • 6
  • m

    Mark Iantorno

    08/14/2020, 5:06 PM
    Does anyone have experience using the
    styledSvg{...}
    ? I am not clear on how to set the .svg file as the src for the image or how to set/change the
    fill
    property of the svg to change the color. Any advice would be appreciated.
    t
    a
    • 3
    • 21
  • v

    Vampire

    08/14/2020, 10:53 PM
    How can we use methods that expect an options object? For example I have included
    @actions/http-client
    and want to use
    HttpClient().post(...
    . The
    ...d.ts
    has
    export interface IHeaders {
        [key: string]: any;
    }
    [...]
    post(requestUrl: string, data: string, additionalHeaders?: ifm.IHeaders): Promise<ifm.IHttpClientResponse>;
    Dukat made from that
    external interface IHeaders {
        @nativeGetter
        operator fun get(key: String): Any?
        @nativeSetter
        operator fun set(key: String, value: Any)
    }
    [...]
    open fun post(requestUrl: String, data: String, additionalHeaders: IHeaders = definedExternally): Promise<IHttpClientResponse>
    My first approach was basically naively following the IDE autocompletion which of course does not work (no additional headers set):
    val response = HttpClient().post(
            requestUrl = "<http://localhost:9999/api/GetFiles>",
            data = "type=ProductId&url=$productId",
            additionalHeaders = object : IHeaders {
                override fun get(key: String): Any? = when (key) {
                    "Content-Type" -> "application/x-www-form-urlencoded"
                    else -> null
                }
    
                override fun set(key: String, value: Any) = error("headers are read-only")
            }
    ).await()
    My next try was to do what my guts suggested and made the compiler happy:
    val response = HttpClient().post(
            requestUrl = "<http://localhost:9999/api/GetFiles>",
            data = "type=ProductId&url=$productId",
            additionalHeaders = mapOf("Content-Type" to "application/x-www-form-urlencoded") as IHeaders
    ).await()
    IJ complains about "Unchecked cast to external interface: Map<String, String> to IHeader" and it also does not work, but sends the additional headers
    _keys_up5z3z$_0: null
    _values_6nw1f1$_0: null
    _keys_qe2m0n$_0: null
    _values_kxdlqh$_0: null
    internalmap_uxhen5$_0: [object Object]
    equality_vgh6cm$_0: [object Object]
    _entries_7ih87x$_0: null
    a
    g
    • 3
    • 12
  • v

    Vampire

    08/15/2020, 8:29 AM
    I just added
    @actions/cache
    to my npm dependencies. Now I get 2285 compile errors because Dukat is creating many duplicated declarations. 😕 Anyone seen this before and has some idea?
    t
    v
    • 3
    • 6
  • d

    Dhirendra Patil

    08/15/2020, 9:06 AM
    We, at GirlScript Pune are looking for mentors who would like to collaborate with us in conducting online sessions and webinars on topics they are passionate about! If you have a love for communities or want to reach a wider audience or just want to spread your love for technology, wait no more and get on board. Register at: https://bit.ly/gsp-mentors Perks: - Certificate of appreciation - Recognition and promotion on all our social media handles. For queries, Email: girlscriptp@gmail.com
    🚓 2
    h
    • 2
    • 1
  • r

    rnentjes

    08/17/2020, 7:02 PM
    In javascript target with the IR backend the properties are named differently in the js objects (with underscores and numbers), they used to be the same as the kotlin property names. Atm switching from legacy to IR breaks my application because I can not send a message anymore (to audio worker) as the json is now different. There is an annoration @JsName but that doesn't seem to work for the IR backend. Is there a way to overwrite these names?
    b
    • 2
    • 5
  • a

    andylamax

    08/17/2020, 8:27 PM
    Why am I getting a vibe that the IR backend is not yet well even with the release of 1.4? Do we still need this work arround? https://kotlinlang.slack.com/archives/C0B8L3U69/p1585318146030900
    b
    b
    a
    • 4
    • 5
  • v

    Vampire

    08/18/2020, 2:17 PM
    With the Kotlin Gradle JS plugin with
    nodeJs
    target, with 1.3.72 there was a
    run
    task automatically. Now with 1.4.0 there is no
    run
    task anymore. You can use
    binaries.executable()
    then you at least get a
    nodeRun
    task, but no
    run
    task. Is that an expected change? I cannot remember having seen this in any of the update blog entries.
    b
    i
    • 3
    • 20
  • r

    Robert Jaros

    08/18/2020, 4:03 PM
    When running tests with IR backend I've noticed my
    jQuery(v)
    is translated to
    jQuery.invoke(v)
    in generated JS file. My
    jQuery
    is defined as
    external val
    . Of course half of my tests are failing with IR (all working fine with legacy backend). Is it a bug?
    • 1
    • 4
  • v

    Vampire

    08/18/2020, 6:35 PM
    If you have something that is documented to be used like this from node.js code:
    require('@vercel/ncc')(input, {
        sourceMap: true
    })
    How do you properly formulate this as externals definition so that it can be used in Kotlin code?
    t
    p
    • 3
    • 10
  • r

    Robert Jaros

    08/18/2020, 8:54 PM
    Legacy compiler backend generate JS objects with fields named exactly like data class property names. For
    data class Foo(val a: Int, val b: String)
    we have
    a
    and
    b
    on the JS side. But new IR backend generates
    _a
    and
    _b
    . I think it will break a lot of code. Is this intentional change?
    ➕ 1
    :yes: 1
    t
    d
    r
    • 4
    • 6
  • r

    Robert Jaros

    08/18/2020, 11:23 PM
    I've finally managed to compile whole KVision with 1.4 IR backend and to build the showcase example with it. And the bundle size is almost 2x larger! What has happened? I made some tests with M1 a few months ago, and it was smaller back then (later with M3 and RC it did not compile because of KT-40083). Anyone tried to build something with 1.4 IR? Does it work ok for you? Can I somehow debug this? I don't see any temporary files from DCE in the build folder.
    • 1
    • 5
  • v

    Vampire

    08/18/2020, 11:58 PM
    Is it expected that with 1.4.0 and
    kotlin { js(IR) { useCommonJs(); binaries.executable(); nodejs() }
    `tasks.compileKotlinJs.get().outputFile.absolutePath`evaluates to
    <project dir>/build/classes/kotlin/main/<project>.js
    but that there are no such files but only a folder
    default
    with content?
    🇳🇴 1
    :yes: 1
    i
    • 2
    • 3
  • v

    Vampire

    08/19/2020, 12:36 AM
    What is the difference between
    compileProductionExecutableKotlinJs
    and
    compileDevelopmentExecutableKotlinJs
    ? According to their
    outputFile
    property they both write to
    <project dir>/build/js/packages/<project>/kotlin/<project>.js
    which per-se is maybe not the best idea already. But what is the difference, I can find neither in the docs.
    ➕ 1
    a
    t
    i
    • 4
    • 7
  • v

    Vampire

    08/19/2020, 9:18 AM
    Now when I do
    gradlew :run
    , I get
    ReferenceError: NodeJS is not defined
    . 😞 First line where it happens is
    var ReadableStream = NodeJS.ReadableStream;
    NodeJS.ReadableStream
    comes from Dukat generated files for
    @actions/http-client
    and is defined in
    kotlinx-nodejs
    0.0.6
    . What do I need to do to have those included properly? If I navigate from the
    http-client
    file via
    Ctrl+Click
    , a (pseudo?-)file inside the
    0_NodeJS.knm
    is opened that does not have any
    @JsModule
    annotation,
    package NodeJS
    and
    @file:JsQualifier("NodeJS")
    .
    v
    • 2
    • 3
  • e

    Eamonn Boyle

    08/19/2020, 10:42 AM
    I'm seeing a strange issue in the initialisation of top level variables. It looks like the generated JS defines the "var"s and then initialises them later. But the order of the initialisation can lead to strange results. I have one piece of code that uses a constant to initialise an object, but it is undefined. Constants file
    val BAT_WIDTH = 8
    Other File
    private val batGeometry = BoxGeometry(BAT_WIDTH, 1.0, 1.0)
    The BAT_WIDTH here is undefined. I can get around the issue by putting my constants in a singleton object, but worried about initialisation order generally now. Any docs on this or anyone know how it works? The generated JS seems to be,
    var batGeometry;
    ...
    var BAT_WIDTH;
    ...
    batGeometry = new BoxGeometry(BAT_WIDTH, 1.0, 1.0);
    ...
    BAT_WIDTH = 8;
    t
    a
    • 3
    • 3
  • r

    Robert Jaros

    08/19/2020, 12:32 PM
    This works with legacy backend but not with IR:
    external interface BtOn {
    }
    
    interface SnOn<T> : BtOn {
        var self: T
    }
    
    @Suppress("UnsafeCastFromDynamic")
    fun on(target: Any): SnOn<Any> {
        val obj = js("{}")
        obj["self"] = target
        return obj
    }
    
    fun main() {
        val x = on("test");
        console.log(x.self);
    }
    It fails with
    x._get_self_ is not a function
    . Is it a bug in the compiler backend or is my code just wrong?
    d
    a
    • 3
    • 4
  • r

    Robert Jaros

    08/19/2020, 12:57 PM
    Next question, I'm using this function to create a JS object instance from JS constructor:
    inline fun <reified T> Any?.createInstance(vararg args: dynamic): T {
        val jsClass = this
        val argsArray = (listOf<dynamic>(null) + args).toTypedArray()
        return js("new (Function.prototype.bind.apply(jsClass, argsArray))").unsafeCast<T>()
    }
    like this:
    external interface Ext
    val constructor: Any = require("...").something // returns a function which should be called with new operator in JS
    val ext: Ext = constructor.createInstance(it)
    It doesn't work with IR anymore. How can I replace this?
    d
    • 2
    • 10
  • r

    Robert Jaros

    08/19/2020, 1:03 PM
    I also use this when I have a
    dynamic
    property which I know is a constructor and should be used with
    new
    . Any other way to force
    new
    in generated JS?
    t
    • 2
    • 1
  • j

    Joost Klitsie

    08/19/2020, 3:27 PM
    I wanna enable the IR backend for the javascript part of my multiplatform project, but with the release candidates it complained a lot about htis
    t
    • 2
    • 11
  • m

    mkosm

    08/19/2020, 5:41 PM
    How can I use
    @JsName("default")
    with the IR backend enabled? I'm getting this error:
    Untitled
    t
    • 2
    • 5
  • r

    Robert Jaros

    08/19/2020, 7:15 PM
    Anyone else has experienced significantly longer webpack build cycle with 1.4.0 (legacy)? With 1.3.72 and with my workaround for KT-32273 it was about 4 seconds between code change and page hot reload in the browser. Now with 1.4 it's about 8 seconds for the same project.
    • 1
    • 4
  • t

    tylerwilson

    08/19/2020, 8:34 PM
    Any examples of running JS tests in MP library? I am getting this error when trying to run gradle task jsNodeTest:
    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Could not determine the dependencies of task ':salonbiz-library:jsTestPackageJson'.
    > NPM Dependencies already resolved and installed
    • 1
    • 1
  • d

    Derek Ellis

    08/19/2020, 11:20 PM
    I have a multiplatform project that has a js target with an
    actual
    implementation of a class marked with
    @JsExport
    and some properties like
    id
    or
    data
    . What I'm trying to do is to make it possible for an instance of this class to be passed to some other js library that uses those properties internally. The library accepts plain JS objects, and I think it might even turn it into JSON for validation or something, but in any case the library can't see those properties since with the new IR compiler they are mangled to
    _id
    and
    _data
    and it can't make use of the computed properties defined on the class.
    @JsExport
    didn't change it, neither did
    external interface
    , so is there any other way to work around this issue? Is this something worth opening an issue for? I don't think there's one dedicated to the name mangling in the new IR compiler yet.
    r
    • 2
    • 2
  • e

    Eamonn Boyle

    08/20/2020, 9:31 AM
    Any equivalent of EnumSet for KotlinJS - I'd like to have a "Flags" type enum that I can do bitwise OR and AND
    😜 1
    🇳🇴 1
    t
    • 2
    • 4
  • s

    Stan Kocken

    08/20/2020, 12:10 PM
    Hey, do you have a very simple example of JS library built from a multiplatform project with 1.4? I updated to 1.4 and I’m struggling to generate it (before I was using
    runDceJsKotlin
    ). I have a
    .js
    file, but everything is obfuscated inside. I just want to have a public API for my
    .js
    library to be used by a web-developer. The
    JsName
    annotation is not helping. I just want to have a simple method called
    compute()
    that calls other kotlin code (shared with other) and callable from a web-developer through a JS library (not node) I would provide.
    r
    • 2
    • 2
  • r

    Robert Jaros

    08/20/2020, 12:48 PM
    I've got such exception in the browser console with 1.4.0 (legacy):
    Error: This marker function should never been called. Looks like compiler did not eliminate it properly. Please, report an issue if you caught this exception.
    How should I report this issue? There is not really much more information but I suppose it comes from serialization.
    u
    o
    • 3
    • 8
  • i

    iari

    08/20/2020, 6:21 PM
    is there any way to format a date according to a format-string like yyyy-MM-DD-hh:mm
    t
    • 2
    • 1
Powered by Linen
Title
i

iari

08/20/2020, 6:21 PM
is there any way to format a date according to a format-string like yyyy-MM-DD-hh:mm
t

turansky

08/20/2020, 6:57 PM
You can use
String.repeat
for custom implementation
View count: 3