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

    Slackbot

    09/09/2021, 11:40 AM
    This message was deleted.
    c
    b
    • 3
    • 2
  • l

    leandro

    09/10/2021, 7:56 PM
    is there something wrong with the following test (on kotlin/js)?
    @Test fun `on zero throws`() {
        assertFailsWith<ArithmeticException> {
          1 / 0
        }
      }
    it fails with the following message “AssertionError: Expected an exception of class ArithmeticException to be thrown, but was completed successfully.”
    e
    • 2
    • 6
  • a

    andylamax

    09/11/2021, 11:08 AM
    Hello there, Currently service.kt [Snippet 1]
    @file:JsExports
    
    external interface ServiceConfiguration {
      var appId: String
      var debug: Boolean?
    }
    
    fun service(config: ServiceConfiguration)
    Yields the following typescript declaration (code out of this context is redacted): [Snippet 2]
    type Nullable<T> = T | undefined | null
    
    export interface ServiceConfiguration {
      appId: string;
      debug: Nullable<boolean> // want this to be optionally provided
    }
    
    export function service(config: ServiceConfiguration);
    After importing this bundled library in typescript, calling [Snippet 3]
    const service = service({ appId: "<app-id>" }) // troubles the ts compiler
    The compiler expects both arguments like so [Snippet 4]
    const service1 = service({ appId: "<app-id>", debug: undefined }) // ts compiler is happy
    const service2 = service({ appId: "<app-id>", debug: true }) // ts compiler still happy
    Question is, how do I make the kotlin compiler to generate [Snippet 5]
    export interface ServiceConfiguration {
      appId: string;
      debug?: boolean // want this to be optionally provided
    }
    instead of the one being generated on [Snippet 2]. So that I may use it as written in [Snippet 3]?
    • 1
    • 1
  • n

    Nikola Milovic

    09/11/2021, 8:41 PM
    Hey guys, with react, how do you decide whether you'd use RComponent, FC function or the RBuilder extension? In regular react I only used functions and arrow functions but then I could return HTML code and put my useStates and logic before that. What's the state of kotlin, I am kinda confused where to put logic and whether to use the classes or the functions. So with these 3 approaches is it up to preference or are there benefits to each one?
    t
    c
    a
    • 4
    • 8
  • a

    andylamax

    09/13/2021, 9:43 AM
    Hi folks, how does one filter javascript test in a KMP project with gradle?
    ./gradlew jsTest --tests integration.*
    Throws with
    Unknown command-line option '--tests'.
    ./gradlew jsBrowserTest --tests integration.*
    runs all the tests (does not filter)
    ./gradlew jsNodeTest --tests integration.*
    runs all the tests (does not filter)
    b
    r
    • 3
    • 5
  • c

    Chukwukammadu Anizoba

    09/13/2021, 11:11 AM
    Hey guys, Any update on a compatible mocking library for Kotlin/JS? Already tried Mockk, but seems that's not supported yet.
    b
    • 2
    • 4
  • p

    Pitel

    09/13/2021, 1:00 PM
    Any idea why I start getting this when I remove
    -Xir-property-lazy-initialization
    ? I thought the lazy init is exeprimental, and stuff might broke with it, not without it. 🤡
    t
    • 2
    • 4
  • r

    Reuben F

    09/14/2021, 11:45 AM
    Hey, does anybody have a robust heuristic they use when wrapping a javascript library? I've wrapped several quite easily, but there are edge cases with others that I don't really understand. For example, https://pouchdb.com/?ref=w3use (npm: pouchdb-browser) looks quite straightforward from the docs, but it doesn't seem to let me apply @JsModule to a package (with a PouchDB object or class), object, class, function, or function property (I get the usual "not a constructor", "not a function", etc). (Right now for this one I made a
    dynamic
    using require (
    val DB = require("pouchdb-browser").default; val db = DB("my_new_db")
    ) and am just delegating to that in a wrapper class, which is fine.) Just an example, but maybe useful to help illustrate the process one can step through to make the JsModule approach work.
    n
    p
    • 3
    • 6
  • n

    Nikola Milovic

    09/14/2021, 11:52 AM
    When trying to run my web app i get "Something went wrong when displaying this page, Error SIGTRAP". Running
    ./gradlew run
    gives no errors, and the devtools are disconnected. How do I go about debugging this? I have no feedback and absolutely no idea what is causing this, gradle is giving me thumbs up and successful tasks for build and run.
    :web-app:browserDevelopmentRun > webpack 5.35.0 compiled successfully in 9236 ms
    t
    • 2
    • 5
  • c

    Chukwukammadu Anizoba

    09/15/2021, 9:27 AM
    Hey guys, any idea how to test coroutines in KotlinJs? Most solutions I've come across workarounds that should potentially work with Kotlin Multiplatform, but not Kotlin/JS on it's own. Tried using the workaround suggested here: https://youtrack.jetbrains.com/issue/KT-22228. However, the
    promise
    keyword doesn't exist in Kotlin/JS alone.
    b
    • 2
    • 3
  • n

    Nicodemus Ojwee

    09/16/2021, 9:31 AM
    Hello everyone, is this a dead project or we expect some updates soon? https://github.com/Kotlin/kotlinx-nodejs
    👀 1
    r
    f
    • 3
    • 5
  • n

    Norbi

    09/16/2021, 6:57 PM
    I get this error when I recompile my Kotlin/JS project in Idea while running it using `jsBrowserDevelopmentRun`:
    Uncaught Error: Module build failed (from ../../node_modules/source-map-loader/dist/cjs.js):
    Error: ENOENT: no such file or directory, open '...idea-project-folder\build\js\node_modules\webpack-dev-server\client\index.js'
    I use Kotlin 1.5.30 with Compose/Web 1.0.0-alpha4-build348. The
    build\js\node_modules\webpack-dev-server
    folder really does not exist. I have already tried setting
    versions.webpackDevServer.version = "4.0.0"
    (I found this hint somewhere), and setting
    config.watchOptions
    but nothing seems to help 😞 Do you have any idea? Thanks.
    :youtrack: 2
    t
    • 2
    • 3
  • r

    Reuben F

    09/16/2021, 11:47 PM
    Does the equivalent of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/toString exist? I.e. can I get at the source after it has been compiled to js?
    t
    • 2
    • 4
  • c

    CLOVIS

    09/17/2021, 8:28 AM
    How do you pass children props to a class component in Kotlin React? Currently, I'm doing:
    child(MyClassComponent::class) {
      child(SomeFunctionalComponent)
    }
    then, in MyClassComponent.render:
    if (...) {
      props.children()
    }
    This works fine with
    run
    , but fails with `browserProductionWebpack`:
    TypeError: _.render is not a function
    b
    • 2
    • 2
  • a

    andylamax

    09/17/2021, 10:28 AM
    Follow up question regarding JsExports. Asking to see if someone already asked so that I may not open a duplicate ticket currently exporting
    val lambdaFunction: (user: User)->Unit
    yields the following typescript definitions
    readonly lambdaFunction: (p0: User)-> void
    Which hurts readability. I would expect it to be exported to
    readonly lambdaFunction: (user: User)-> void
    Is there already a ticket for this?
    b
    • 2
    • 10
  • p

    peekandpoke

    09/17/2021, 1:37 PM
    Hello there! I am trying to switch the Javascript part of multi-platfatform library to IR. But now things do not compile anymore and I get the error below. Does anyone know what is going on there? Things work fine with the Legacy compiler.
    > Task :commonmp:compileKotlinJs FAILED
    e: org.jetbrains.kotlin.util.KotlinFrontEndException: Front-end Internal error: Failed to analyze declaration TypedAttributes
    File being compiled: (3,1) in .../TypedAttributes.kt
    The root cause java.lang.AssertionError was thrown at: org.jetbrains.kotlin.builtins.KotlinBuiltIns$3.invoke(KotlinBuiltIns.java:93)
            at org.jetbrains.kotlin.resolve.ExceptionWrappingKtVisitorVoid.visitDeclaration(ExceptionWrappingKtVisitorVoid.kt:43)
            at org.jetbrains.kotlin.psi.KtVisitorVoid.visitDeclaration(KtVisitorVoid.java:453)
            at org.jetbrains.kotlin.psi.KtVisitorVoid.visitDeclaration(KtVisitorVoid.java:21)
            at org.jetbrains.kotlin.psi.KtVisitor.visitNamedDeclaration(KtVisitor.java:398)
            ...
    Caused by: java.lang.AssertionError: Built-in class kotlin.Any is not found
            at org.jetbrains.kotlin.builtins.KotlinBuiltIns$3.invoke(KotlinBuiltIns.java:93)
            at org.jetbrains.kotlin.builtins.KotlinBuiltIns$3.invoke(KotlinBuiltIns.java:88)
            at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunction.invoke(LockBasedStorageManager.java:578)
            at org.jetbrains.kotlin.storage.LockBasedStorageManager$MapBasedMemoizedFunctionToNotNull.invoke(LockBasedStorageManager.java:651)
            at org.jetbrains.kotlin.builtins.KotlinBuiltIns.getBuiltInClassByName(KotlinBuiltIns.java:223)
            at org.jetbrains.kotlin.builtins.KotlinBuiltIns.getAny(KotlinBuiltIns.java:228)
            ...
    • 1
    • 1
  • y

    Yan Pujante

    09/18/2021, 5:34 PM
    I have a kotlin/js project that generates code based on skeleton files by doing only simple replacements (replace "[-name-]" with name coming from user input for example). I end up processing .h, .cpp, readme, etc... (live here https://jamba.dev/quickstart/web/) Of course now I want to make it more sophisticated and have if/loop in my "replacement" so clearly a search/replace strategy won't work... any idea of a lightweight project that would work with kotlin js?
    r
    • 2
    • 3
  • y

    Yan Pujante

    09/19/2021, 8:15 PM
    I am trying to use squirrelly in my program but was unable to import it as Kotlin, so reverting to use dynamic:
    val templateEngine: dynamic = js("Sqrl")
     templateEngine.render(content, tokens)
    The issue is that
    tokens
    is a
    Map<String, String>
    and Sqrl is not happy with it... I used this code to workaround the issue:
    val data: dynamic = js("{}")
    tokens.forEach { e -> val k = e.key; val v = e.value; js("data[k] = v") }
    templateEngine.render(content, data)
    which works... But this seems so hacky. Is there a better way?
    :yes: 1
    t
    • 2
    • 5
  • r

    Rescribet

    09/20/2021, 7:59 AM
    Is it possible How to change the nodejs version that is used to run webpack? It uses 14/LTS even when changing the system default to 16
    :yes: 1
    r
    • 2
    • 3
  • s

    salomonbrys

    09/20/2021, 11:55 AM
    Hey guys, I’m compiling a lib that is supposed to be consumed by TypeScript. How do I export a
    Long
    to JS with the IR compiler ???
    @JsExport
    fun long(): Long = 0x12_34_56_78_9A_BC_DE_F0
    Calling this
    long
    function with typescript returns the following object:
    Long { _low: -1698898192, _high: 305419896 }
    Casting to int does NOT do the trick as the compiler overflows :
    @JsExport
    fun int(): Int = 0x12_34_56_78_9A_BC_DE_F0.toInt()
    Calling this
    int
    function with typescript returns a negative number:
    -1698898192
    How can I export a
    Long
    ?
    h
    s
    • 3
    • 5
  • c

    cafonsomota

    09/20/2021, 2:04 PM
    Hello! I’m trying to reduce the size of a multiplatform library that I want to use on a web project, and even after enabling the IR compiler and divided into sub-modules it’s still too big to be used on a browser (~3MB). While doing some tests, with a clean project (with only the greeting function), I’ve noticed: • library is smaller with kotlin 1.5.10 • adding ktor (without making any call), automatically adds the kotlinx.atomicfu to the .js output Is there any possibility to manually exclude it? I’m also listening for solutions on how I can reduce it’s size 🙂
    💯 5
    a
    r
    t
    • 4
    • 5
  • p

    Pitel

    09/21/2021, 7:51 AM
    Is there some article about best practices for Kotlin/JS development? Something like use simple arrays when possible, use external interfaces instead of data classes, etc.?
    👀 1
    h
    a
    t
    • 4
    • 5
  • a

    ankushg

    09/22/2021, 8:04 PM
    Hey friends! I'm migrating to the JS IR compiler and had a question: We previously had some "js interface tests" in our
    jsTest
    sourceset which would basically do something ugly like:
    js("""
      var assert = require('assert');
      var moduleUnderTest = require('myGroup-myModule');
      assert(moduleUnderTest.method("parameter") == expectedResponse);
    """)
    While a little janky, this kind of test let us verify that things like JsName were added where expected and that we didn't accidentally break the public API for our JS consumers. Now, under JS IR, the
    require
    for my module is failing, because there's no JS file in the expected path. There is a package.json though. Does anyone know how to get the module import working again under IR? I'd also be happy to replace this with a JS file (instead of using
    js()
    ) that actually uses the final JS artifacts if anyone has an example of a project that does that! EDIT: it looks like I can remove the
    require(…)
    and get some stuff working, but not everything...
    b
    • 2
    • 10
  • a

    ankushg

    09/22/2021, 11:53 PM
    After bumping to the JS IR Compiler (and Kotlin 1.5.31) I'm running into a compiler error that I can't seem to track down when compiling a specific test compilation. All of my main compilations, and all of my other test compilations seem to compile and run just fine. Does this look like a known issue to anyone? Does anyone know if there's a logfile lingering somewhere that might give me some more details? Truncated stacktrace below -- full stacktrace in thread.
    > Task :my-module:compileTestDevelopmentExecutableKotlinJs FAILED
    e: java.lang.NullPointerException
    	at org.jetbrains.kotlin.ir.backend.js.transformers.irToJs.IrElementToJsStatementTransformer.visitCall(IrElementToJsStatementTransformer.kt:132)
    	at org.jetbrains.kotlin.ir.backend.js.transformers.irToJs.IrElementToJsStatementTransformer.visitCall(IrElementToJsStatementTransformer.kt:20)
    
    * What went wrong:
    Execution failed for task ':my-module:compileTestDevelopmentExecutableKotlinJs'.
    > A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
       > Internal compiler error. See log for more details
    a
    r
    • 3
    • 11
  • p

    Pitel

    09/24/2021, 11:32 AM
    I have a plenty of DTO `data class`es from our backend team (so Ican't change them). I need to serialize some of them to GraphQL, so I'm writing custom serializers:
    val MessageTemplateTextDtoCreateInput.gql
        get() = buildString {
            append('{')
            appendKV("body", body)
            appendKV("languageId", languageId)
            appendKV("subject", subject, true)
            append('}')
        }
    
    fun StringBuilder.appendKV(key: CharSequence, value: Any?, last: Boolean = false) {
        append(key)
        append(':')
        if (value is String) {
            append('"')
        }
        append(
            when (value) {
                is Array<*> -> value.joinToString(",", "[", "]") {
                    it.asDynamic().gql as? CharSequence ?: "" // !!! PROBLEM HERE !!!
                }
                else -> value
            }
        )
        if (value is String) {
            append('"')
        }
        if (!last) {
            append(',')
        }
    }
    The problem is, how can I dynamicaly get the
    .gql
    extension value I created? • I understand, that Kotlin can't know from
    Array<*>
    that the members has the
    .gql
    extension. • I know I can't use rflection in JS to look if the extension is there. • Sealed classes/interfaces might be the solutionm, but I can't change the DTOs. •
    asDynamic().gql
    does not work (this is a bit WTF to me, I thought this might work and at worst throw an exception or something.) So, any idea how to do this?
    t
    • 2
    • 3
  • r

    Rohan Maity

    09/26/2021, 11:42 AM
    Hello How can I configure Kotlin/JS so that in
    webpack.config.js
    I will be able to set custom file name (instead of webApp.js)
    b
    • 2
    • 9
  • p

    Piotr Krzemiński

    09/27/2021, 8:21 AM
    Normally this channel is full of questions, issues, bug reports. I just want to give kudos to the Kotlin team that makes using :kotlinnew: Kotlin for :js: possible. Great job folks, keep up the great work! 💪 Thanks to you, I actually like web development. I can't wait for K/JS to be a real, prod-ready alternative for TS. It already makes a difference for some projects and I heard this surprise "wow, so Kotlin works for JS?" multiple times. Let's bring proper type-safety to the web dev world 😄
    ➕ 14
    :thank-you: 5
    c
    • 2
    • 1
  • j

    jush

    09/27/2021, 12:52 PM
    I'm using npm-publish plugin (by Martynas Petuška) and after I upgraded to Kotlin 1.5.30 the
    packages.json
    generated has neither
    dependencies
    nor
    bundledDependencies
    entries. Do we need to explicitly set those from now on?
    b
    • 2
    • 49
  • d

    Dra

    09/27/2021, 5:24 PM
    Hi everyone ! So I was trying to push a little project to github pages, everything works fine locally but when I try to deploy it, it fails on the
    testing
    part saying this :
    > Failed to execute all tests:
      :browserTest: java.lang.IllegalStateException: Errors occurred during launch of browser for testing.
      - Opera
      - Firefox
      - Chromium
      Please make sure that you have installed browsers.
      Or change it via
      browser {
          testTask {
              useKarma {
                  useFirefox()
                  useChrome()
                  useSafari()
              }
          }
      }
    I know that the issue is related to the fact that it can't find firefox / chromium / opera... But how can I make it so tests are run correctly when deploying without having to remove the whole UI related part in my tests ?
    r
    b
    e
    • 4
    • 5
  • t

    Todd

    09/28/2021, 3:48 PM
    Hello all! If I want to extend a external class with some es6+ apis, what is the proper way to do that? I tried to do an extension function (although I know that doesn't really makes sense) like
    external fun Blob.stream(): Promise<ReadableStream>
    But the compiler told me that's illegal. Intellij suggested I change it to
    @Suppress("NOTHING_TO_INLINE")
    inline fun Blob.stream(): Promise<ReadableStream> = asDynamic().stream() as Promise<ReadableStream>
    which I think will work for me, but I was wondering if anyone knows of a better way to do this?
    t
    • 2
    • 4
Powered by Linen
Title
t

Todd

09/28/2021, 3:48 PM
Hello all! If I want to extend a external class with some es6+ apis, what is the proper way to do that? I tried to do an extension function (although I know that doesn't really makes sense) like
external fun Blob.stream(): Promise<ReadableStream>
But the compiler told me that's illegal. Intellij suggested I change it to
@Suppress("NOTHING_TO_INLINE")
inline fun Blob.stream(): Promise<ReadableStream> = asDynamic().stream() as Promise<ReadableStream>
which I think will work for me, but I was wondering if anyone knows of a better way to do this?
t

turansky

09/28/2021, 4:01 PM
Type already known, no cast required:
inline fun Blob.stream(): Promise<ReadableStream> =     asDynamic().stream().unsafeCast<Promise<ReadableStream>>()
Extension - most Kotlinish solution
t

Todd

09/28/2021, 6:01 PM
Interesting. Extension functions feel more like an implementation then defining an external interface so I felt like there might be something else (without redefining the whole clas). But this works! Thanks!
t

turansky

09/28/2021, 6:10 PM
FYI - Type-safe sugar
👍 1
View count: 5