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

    SecretX

    08/06/2022, 8:34 PM
    I decided to build a Kotlin Plugin compiler to learn more about bytecode. I planned to build a plugin that adds a
    serialVersionUID
    (example below) to Kotlin classes that implement (or inherit from)
    java.io.Serializable
    . I know the compiler already creates those, but I wanted to simulate that (and maybe change the value to experiment with it). I got the Gradle plugin and subplugin finished, alongside the
    CommandLineProcessor
    and
    ComponentRegistrar
    . The only part left is to figure out how to: - Detect/find if the class already has a
    serialVersionUID
    variable declared - Add the
    serialVersionUID
    exactly as it is below to the declaration of the class And this last task is the one I can't figure out how to do. Should I use a
    ClassBuilderInterceptorExtension
    , a
    ExpressionCodegenExtension
    , or something else entire (because I saw there are bunchs of IR-somethings extensions to do a lot of things), what of those would be more appropriate for this purpose? And second, how to actually add fields to a class using these extensions?
    private static final long serialVersionUID = 1L;
    t
    • 2
    • 1
  • r

    reactormonk

    08/08/2022, 9:43 AM
    Can I test for
    when
    exhaustiveness without assigning the result to a variable?
    val x: Unit =
    feels a bit silly.
    w
    e
    j
    • 4
    • 8
  • j

    Jerry Yion

    08/08/2022, 12:33 PM
    Hi all, I am just wondering what causes the issue below
    "Class ... is compiled by a pre-release version of Kotlin and cannot be loaded by this version of the compiler
    e
    • 2
    • 3
  • n

    natario1

    08/08/2022, 6:15 PM
    How can I read annotation default values in ir? I have
    @Foo(val foo: Bool = true)
    . I tried with
    annotation.symbol.owner.valueParameters[0].defaultValue!!.expression as IrConst<Bool>
    , but the expression is actually an IrErrorExpression saying
    "Stub expression for default value of foo"
    .
  • n

    natario1

    08/08/2022, 6:42 PM
    My compiler plugin has a companion runtime library. Some functions there have complex logic used by the plugin just because it would be hard to write it in IR. Is there a way to hide these functions from the end user though? For example, I scoped them inside an object to reduce their discoverability, but I’m thinking there must be some better solution.
    j
    • 2
    • 2
  • m

    murdock

    08/12/2022, 11:58 PM
    Hey folks, if anyone is looking for a simple compiler plugin, I created this one that essentially fires a callback at runtime, every time annotated function is called. Could be useful for debugging, analytics, compose etc.
    g
    • 2
    • 4
  • r

    rrva

    08/15/2022, 10:44 AM
    Anyone seen issues with incremental compilation in 1.7.x where KotlinCompileDaemon never finishes call to LookupSymbolKeyDescriptor.read? https://youtrack.jetbrains.com/issue/IDEA-299961
    • 1
    • 1
  • y

    Youssef Shoaib [MOD]

    08/19/2022, 10:42 AM
    When I use Evaluate Expression while debugging, Intellij doesn't take into account any enabled compiler plugins. Is this a misconfiguration on my end, or is there simply no way to use compiler plugins in Evaluate Expression?
    d
    • 2
    • 4
  • j

    Jan Skrasek

    08/20/2022, 8:14 AM
    I'd like to check if reified generic T is implementing an interface.
    interface Destination {}
    interface Dialog : Destination {}
    
    inline fun <reified T : Destination> add() {
       val isDialog1 = T is Dialog // does not compile
       val isDialog2 = Dialog::class.java.isAssignableFrom(T::class.java) // works, but uses Java reflection
       val isDialog3 = (typeOf<T>().classifier as KClass<T>).isSubclassOf(Dialog::class) // works, but uses Kotlin full reflection, doesn't it?
    }
    Isn't there any compiler optimized way to do this? But THB, I'm not including kotlin full reflection to my dependencies, so maybe the third way IS optimized?
  • n

    natario1

    08/21/2022, 8:45 AM
    Compiler plugin question - what does this error mean?
    e: java.lang.UnsupportedOperationException: VALUE_PARAMETER INSTANCE_RECEIVER name:<this> type:my.sample.ProblematicCallbackImpl
            at org.jetbrains.kotlin.backend.konan.llvm.CodeGeneratorVisitor$TopLevelCodeContext.unsupported(IrToBitcode.kt:253)
    I identified the offending code (
    irGet(thisClass.thisReceiver!!)
    ) but not a solution. I’m using the receiver to call a superclass function. I tried using
    superClass.thisReceiver!!
    instead, but that creates a different error.
    i
    • 2
    • 2
  • j

    jw

    08/23/2022, 11:45 PM
    When is the legacy JVM backend slated to be removed?
    r
    y
    u
    • 4
    • 3
  • a

    Askhar Aydarov

    08/26/2022, 1:19 PM
    Hi, everyone. I have a couple of questions about compiler plugins. 1. Is there any way to uniquely identify function calls so that the identifier is not changeable until the place of the function call changes? 2. Is it possible to get information about previous compilations during incremental compilation?
    t
    • 2
    • 2
  • m

    majindong

    08/27/2022, 11:03 AM
    Hello everyone,I want to add a new property to a class named "mjd", I can see the property after using dump() function (in the bottom of the following result).But when I test this compiler plugin, it can not find this new property. Does anyone know the reason? CLASS CLASS name:A modality:FINAL visibility:public superTypes:[kotlin.Any] annotations: DebugLog $this: VALUE_PARAMETER INSTANCE_RECEIVER name:<this> type:<root>.A CONSTRUCTOR visibility:public <> () returnType:<root>.A [primary] BLOCK_BODY DELEGATING_CONSTRUCTOR_CALL 'public constructor <init> () [primary] declared in kotlin.Any' INSTANCE_INITIALIZER_CALL classDescriptor='CLASS CLASS name:A modality:FINAL visibility:public superTypes:[kotlin.Any]' FUN FAKE_OVERRIDE name:equals visibility:public modality:OPEN <> ($this:kotlin.Any, other:kotlin.Any?) returnType:kotlin.Boolean [fake_override,operator] overridden: public open fun equals (other: kotlin.Any?): kotlin.Boolean [operator] declared in kotlin.Any $this: VALUE_PARAMETER name:<this> type:kotlin.Any VALUE_PARAMETER name:other index:0 type:kotlin.Any? FUN FAKE_OVERRIDE name:hashCode visibility:public modality:OPEN <> ($this:kotlin.Any) returnType:kotlin.Int [fake_override] overridden: public open fun hashCode (): kotlin.Int declared in kotlin.Any $this: VALUE_PARAMETER name:<this> type:kotlin.Any FUN FAKE_OVERRIDE name:toString visibility:public modality:OPEN <> ($this:kotlin.Any) returnType:kotlin.String [fake_override] overridden: public open fun toString (): kotlin.String declared in kotlin.Any $this: VALUE_PARAMETER name:<this> type:kotlin.Any FUN name:track visibility:public modality:OPEN <> ($this:<root>.A) returnType:kotlin.String $this: VALUE_PARAMETER name:<this> type:<root>.A PROPERTY name:mjd visibility:public modality:FINAL [val] FIELD PROPERTY_BACKING_FIELD name:mjd type:kotlin.Long? visibility:private EXPRESSION_BODY CONST Long type=kotlin.Long value=1 FUN DEFAULT_PROPERTY_ACCESSOR name:<get-mjd> visibility:public modality:FINAL <> ($this:<root>.A) returnType:kotlin.Long? correspondingProperty: PROPERTY name:mjd visibility:public modality:FINAL [val] $this: VALUE_PARAMETER INSTANCE_RECEIVER name:<this> type:<root>.A BLOCK_BODY RETURN type=kotlin.Nothing from='public final fun <get-mjd> (): kotlin.Long? declared in <root>.A' GET_FIELD 'FIELD PROPERTY_BACKING_FIELD name:mjd type:kotlin.Long? visibility:private' type=kotlin.Long? origin=null receiver: GET_VAR '<this>: <root>.A declared in <root>.A.<get-mjd>' type=<root>.A origin=null
    n
    • 2
    • 5
  • h

    holgerbrandl

    08/29/2022, 2:35 PM
    Hi, when creating an inherited class within a function that refers to properties of the parent scope, it creates a constructor which is somehow reported to be-zero arg, but when creating an instance, it turns out it is not:
    import kotlin.reflect.KClass
    
    
    open class Provider {
    
        open fun computeSmthg() = 42
    }
    
    class ConfigBuilder(val other: Int = 32) {
    
        fun asProvider(): KClass<*> {
    
            class CustomProvider : Provider() {
    
                override fun computeSmthg(): Int {
                    return other
                }
            }
    
            return CustomProvider::class
        }
    }
    
    fun main() {
    
        val providerClass = ConfigBuilder().asProvider()
    
        require(providerClass.constructors.first().parameters.isEmpty())
    
        val constructor = providerClass.constructors.first()
        println(constructor.parameters)
        println(constructor)
    
        println(constructor.call())
    }
    which fails with
    fun <init>(): com.systema.nexperia.epi.solver.`ConfigBuilder$asProvider$CustomProvider`
    Exception in thread "main" java.lang.IllegalArgumentException: Callable expects 1 arguments, but 0 were provided.
    Could I rewrite the code from above to actually create CustomProvider with a zero-arg constructor while referring to
    òther
    property?
    t
    • 2
    • 4
  • t

    Tóth István Zoltán

    08/31/2022, 5:09 AM
    Huh, I see that function references generate one class per use site for JVM. Is this something unavoidable? The reference has to store the receiver, so I guess a new instance creation is unavoidable, but I guessed it will be one general class, not one per use site.
    class E {
        fun b1() = Unit
        val b = B(this::b1)
        val c = B(this::b1)
    }
    
    class B(
        val func: () -> Unit
    )
    Results in 4 classes: • B.class • E.class • E$b$1.class • E$c$1.class In my specific use case I have a number of compiler plugin generated functions I pass, like in the example below. I could write a workaround by generating one function that gets the instance of E and an integer index and uses a
    when
    to select the appropriate function. But that feels like a bit forced.
    class E {
       fun a1() = Unit
       fun a2() = Unit
       init {
          B(this::a1)
          B(this::a2)
       }
    }
    u
    • 2
    • 1
  • d

    David Bieregger

    08/31/2022, 12:18 PM
    I was just wondering if it would be worth the effort creating a interoperability layer between intellisense and compiler. So that while you code the knowledge the intellisense gains, can directly be used by the compiler. And vice versa, the intellisense can hot start upon the last cache of the compiler. So that all the information doesn't need to be cached twice. Maybe you could also start compiling small changes in the background so that when you just make a little change the compiler only needs to pack the executable together and is ready to go. With optimizations to gradle this could also improve developer experience with Kotlin/JS and continous development. Personally i find it a bit annoying that it takes so long to apply the changes, maybe you can kill multiple birds with one stone there.
    t
    • 2
    • 1
  • p

    PHondogo

    09/02/2022, 9:37 AM
    Hello! How to deep copy IrElement with remaping some symbols?
    s
    • 2
    • 1
  • n

    natario1

    09/02/2022, 3:49 PM
    Hello 👋 I have some doubts about expect/actual support in IR plugins. For functions, for example: • I can see
    IrFunction.isExpect
    , but how to retrieve the actual (assuming they are compiled together)? Do I need a full module lookup, looking for a function with the same fq name? • Given an IrFunction, how to implement
    IrFunction.isActual
    ?
  • m

    majindong

    09/03/2022, 9:11 AM
    Hello everyone, I want to change the modality of property from final to abstract. Does anybody how to do this? many thanks!
  • s

    Shreyash Saitwal

    09/06/2022, 9:21 AM
    Hi, how should I use the command-line compiler to perform incremental compilation?
  • x

    Xavier F. Gouchet

    09/06/2022, 9:43 AM
    Hello, I'm thinking about writing a compiler plugin to transpile kotlin to another language, but most tutorials and videos I find around that are several years old. Is there a more recent documentation, maybe more specifically around the code generation step, i.e. converting IR into a custom language?
    e
    d
    b
    • 4
    • 11
  • r

    reactormonk

    09/07/2022, 8:25 AM
    Huh, no forward knot tying or whatever it's called with mutually recursive functions inside a body?
    setContent {
      ...
      suspend fun func1() {
        func2()
      }
      suspend fun func2() {
        func1()
      }
    }
    Tells me
    func2
    isn't defined in
    func1
    d
    y
    • 3
    • 3
  • b

    Benni

    09/07/2022, 8:38 PM
    Hi friends. I am working with Kotlin embedded compiler and I have a
    org.jetbrains.kotlin.psi.KtNamedFunction
    . Anyone know how I can get the line number in which the function resides. I can get the location with
    startOffsetSkippingComments
    and I assume I could calculate it myself by reading the file, but I was wondering, if there might be a different way.
    a
    • 2
    • 1
  • p

    Peter

    09/08/2022, 7:19 AM
    Are the new Kotlin compilers multi-platform? In other words, can I compile the compiler to JS (or web-assembly in the future) so I can run the compiler itself in a browser. Perhaps already documented somewhere but couldn’t find it.
    d
    • 2
    • 1
  • a

    August Lilleaas

    09/08/2022, 7:23 AM
    in ktor-server-html-builder-jvm, there’s an interesting Kotlin detail that I’m wondering if anyone here knows more about:
    respondHtml(status) { with(template) { apply() } }
    . The use of
    with
    here seems to be used to make sure that
    apply()
    refers to the method that’s defined as a method on
    HTML<T>
    that
    template
    implements. If you write
    template.apply()
    it resolves to the built in scope function
    apply
    . What is it about the use of
    with
    that makes Kotlin invoke the
    apply
    method on
    HTML<T>
    rather than the scope function?
    b
    • 2
    • 15
  • g

    Gasan

    09/09/2022, 4:12 PM
    Hi here. If i compile kotlin source that depends on java source (not compiled yet), are there any restrictions on the java source? I know that if it uses lombok, i must use lombok plugin, but things like java language version? Also, would i be significantly down on a compile time if the most files in the maven module are java and only a few kotlin? Is it ok to have such a mixed module? Thanks a lot.
    d
    • 2
    • 1
  • n

    natario1

    09/10/2022, 10:07 AM
    Is it expected that a sealed interface can be implemented from any package (and any module I suspect) by using delegation? E.g.
    Bar : Foo by FooImpl()
    . Here Bar is a Foo without being a FooImpl, so it feels like it is a new direct implementation.
    d
    • 2
    • 2
  • a

    August Lilleaas

    09/10/2022, 11:07 AM
    random thought of the day: it would be cool if Kotlin had a feature where annotations could apply super powers to a scope so that the file would compile even if the code in that scope doesn’t compile. Use case: tests annotated with
    @Test
    , if it doesn’t compile, the test fails, but the other tests still run
    e
    • 2
    • 6
  • p

    PHondogo

    09/10/2022, 12:08 PM
    Hello! How can i change IrField from val to var during transformation by compiler plugin? isFinal property of IrField is readonly.
    m
    • 2
    • 2
  • c

    Chachako

    09/10/2022, 6:18 PM
    Can the K2 plugin be used alongside the old compiler plugin? (from the user’s point of view)
    y
    d
    • 3
    • 10
Powered by Linen
Title
c

Chachako

09/10/2022, 6:18 PM
Can the K2 plugin be used alongside the old compiler plugin? (from the user’s point of view)
y

Youssef Shoaib [MOD]

09/10/2022, 6:33 PM
Yes since it just depends on whether the compiler argument for K2 is passed in or not. Your k2 plugin will most likely even be included in the same
ComponentRegistrar
, so yes it is compatible. Just be careful though that your IR backend needs to be able to handle code both from the old FE frontend and also the FIR (K2) frontend
c

Chachako

09/11/2022, 6:24 AM
So can I also apply the old compiler plugin (compose) that does not support K2 at the same time, and the new compiler plugin developed with K2 API?
y

Youssef Shoaib [MOD]

09/11/2022, 10:50 AM
Yes, but a user won't be able to use both at the same time IF compose relies on the old frontend. Basically, the backend right now is unified (it's all IR) and that is the same for K2, but the frontend is different, meaning that if Compose does some frontend shenanigans (which I think it might do? for like preventing you from calling
@Composable
functions outside of non-Composables) then you might find weird errors happening. Compose also most likely will receive a K2 update since again they don't rely on frontend that extensively AFAIK.
c

Chachako

09/11/2022, 2:24 PM
Thank you for your explanation!
d

dmitriy.novozhilov

09/12/2022, 8:57 AM
Also note that even pure backend plugins may use some API (descriptors and
BindingContext
) which are deprecated but still accessible in combination of FE 1.0 + IR backend So authors of those plugins should fix them before marking plugin as K2 compatible
c

Chachako

09/12/2022, 2:34 PM
In fact, I’m just going to use the K2 API to develop a compiler plugin for my own use, but at the same time, I use many other old compiler plugins (compose, realm-kotlin), which have not yet supported K2. So I’m just afraid that I can’t use them at the same time. 😶
d

dmitriy.novozhilov

09/12/2022, 3:08 PM
In such setup you could not use everything at once
c

Chachako

09/12/2022, 4:10 PM
In such setup you could not use everything at once
Uh... Do you mean that the following will fail? So I have to wait for other plugins to support the K2 API?
plugins {
    id("org.jetbrains.compose") // Old compiler
    id("io.realm.kotlin") // Old compiler
    id("my.k2.compiler.plugin") // K2 compiler
}
d

dmitriy.novozhilov

09/13/2022, 7:46 AM
Yep. If you compiler your project with K2, only
my.k2.compiler.plugin
will work With K1 compiler only
compose
and
realm
But if you enable some plugin with both frontends support (e.g.
allopen
) then it will work with both frontends
View count: 16