https://kotlinlang.org logo
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
  • a

    Alireza Ahmadi

    04/06/2020, 11:13 AM
    Hello, I am writing a compiler plugin to modify errors and warnings found by the compiler. I have a code like this, that can read the diagnostics
    class WarnningsExtension(
    ) : AnalysisHandlerExtension {
    
        override fun analysisCompleted(project: Project, module: ModuleDescriptor, bindingTrace:
        BindingTrace, files: Collection<KtFile>): AnalysisResult? {
    
            val diagnostics = bindingTrace.bindingContext.diagnostics
            return AnalysisResult.Companion.success(bindingContext, module)
        } 
    }
    But, I also want to modify this list like
    val newDiagnostics = diagnostics.filter { //myFilter }
    And return this result back instead. Is something like this possible? Or is there any extension that allow me to modify diagnostics?
    r
    • 2
    • 6
  • h

    Hadi Lashkari

    04/10/2020, 3:15 PM
    Hey I've created https://github.com/hadilq/trackable-compiler-plugin and all the tests in the sample project and android sample tests are passing. You can simply check it by running
    ./gradlew clean check
    , but when I tried it on a simple new android project created by AS, the same tests throw
    NoSuchMethodException: com.github.hadilq.emptycomposeandroid.TrackableClass.track()
    I have to add that it seems the compiler plugin is installed because it compiles without
    Unresolved ...
    , but at the runtime there is no generated method! Any idea would be appreciated. Thank you for your time 🙂
    • 1
    • 2
  • r

    rbares

    04/12/2020, 3:44 PM
    Hi, How can I run the tests for the android extensions compiler plugin (in
    plugins/android-extensions-compiler
    )? I have a patch ready to fix a major bug but can't find a relevant gradle task or IDEA configuration to run the tests. If I can update these tests I hope to raise a pull request within the week
    u
    • 2
    • 8
  • r

    ralf

    04/12/2020, 11:07 PM
    Are there ways to modify existing code? Specifically, I’m trying to remove an annotation from a class or to modify it:
    // Original:
    @MyAnnotation(values = ["a", "b"]
    class MyClass
    
    // Expected:
    @MyAnnotation(values = ["a", "b", "c"]
    class MyClass
    I couldn’t find a hook to do this. I only found ways add a new annotation. Any pointers?
    s
    • 2
    • 2
  • r

    rocketraman

    04/16/2020, 6:25 PM
    I've recently enabled the new inference algorithm with the Kotlin 1.4 nightly (1.4.0-dev-6071) compiler. I have an inline function that calls some Java code with signature:
    public <T> T deserialize(..., final Type type)
    like this:
    inline fun <reified T: Set<Any?>> deser(...): T? = deserialize(..., object : TypeToken<T>() {}.type)
    and this used to work fine with 1.4-M1 / old inference. However, now I get a runtime error when the java code attempts to return its value to the Kotlin code:
    Caused by: java.lang.ClassCastException: class java.util.LinkedHashSet cannot be cast to class java.lang.Void (java.util.LinkedHashSet and java.lang.Void are in module java.base of loader 'bootstrap')
    I can "solve" this by explicitly adding the
    T
    type to the deserialize call i.e.
    deserialize<T>(...)
    , but I'm wondering if this is a bug with the new type inference? The compiler does not report any errors if the
    <T>
    is left off.
    m
    • 2
    • 7
  • r

    rocketraman

    04/17/2020, 7:58 PM
    Poll: what should (note: not, what does) this code produce? (Hint: it produces 1️⃣ in Kotlin 1.4-dev with new inference enabled)
    fun <T> foo(): T? = "abc" as T
    
    fun main() {
      val s: String? = if(false) null else foo()
    }
    1️⃣ A runtime exception
    ClassCastException: class java.lang.String cannot be cast to java.lang.Void
    2️⃣ A compile-time error due to the type
    T
    of
    foo
    being ambiguous (could be
    String?
    or could be
    Nothing
    ) 3️⃣ A compile-time warning that the type of
    T
    was inferred to
    Nothing
    and that is probably not the desired result 4️⃣ An inference of
    T
    to be
    String?
    , so no compile-time or runtime errors 5️⃣ Other
    2️⃣ 3
    4️⃣ 5
    m
    • 2
    • 2
  • d

    Drew Hamilton

    04/20/2020, 8:38 AM
    1. I notice that when I declare a
    private companion object
    , the
    Companion
    class is compiled as package-private in the bytecode, but the static
    Companion
    field is compiled as public + deprecated in the bytecode. Why is this? 2. Because of this, in the IDE, from a Java call-site, I can can compile and run
    Object object = DeferredBoolean.Attribute.Companion;
    without issue. The
    Companion
    field doesn’t even get a strikethrough, which seems like an IDE bug. Assuming this hasn’t already been fixed in a new IDE version, and depending on the answer to #1, should I file an IDE bug?
    u
    • 2
    • 3
  • m

    mattmoore

    04/21/2020, 9:55 PM
    Is there a way to make the Kotlin compiler list its phases? In Scala, for example, I can run
    scalac -Xshow-phases
    to get something like this:
    phase name  id  description
        ----------  --  -----------
            parser   1  parse source into ASTs, perform simple desugaring
             namer   2  resolve names, attach symbols to named trees
    packageobjects   3  load package objects
             typer   4  the meat and potatoes: type the trees
    👆 2
    d
    b
    u
    • 4
    • 5
  • b

    bjonnh

    04/22/2020, 12:14 AM
    I may have hit a compiler bug. If I use the HTML DSL in my project with tbody { tr{ td{ }}} , the more tr I add in my code , the slower it compiles. Having one it compiles in ~30s, adding another one it takes 1min30, and I stopped it after 4 min when I have three… (edited)
    m
    i
    m
    • 4
    • 23
  • r

    ralf

    04/23/2020, 11:20 PM
    Am I missing something obvious? I feel like compiler plugins can easily break with incremental compilation. My plugin generates a new Kotlin file when another file contains an annotation. I add the plugin with
    dependencies {
      kotlinCompilerPluginClasspath project(':myplugin')
    }
    If I change something in my compiler plugin, then I see that the Kotlin compilation tasks aren’t up to date, because my compiler plugin changed. Good! The problem now is that the incremental compilation kicks in and doesn’t recompile the code in the module, because nothing has changed for the source files individually, only the Kotlin compiler plugin dependency has changed. Is there a way to recompile a module, if one of its compiler plugins has changed? (I tested disabling incremental compilation and this fixes the problem. But I’m afraid of the slow compilation long term.)
    s
    • 2
    • 3
  • l

    lhwdev

    04/28/2020, 1:00 AM
    Where can I find kotlin idea plugin dependency like
    org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors
    ? I could find it in the kotlin source code, but I don't know how to add the dependency.
    t
    • 2
    • 23
  • a

    Ahmed Mourad

    05/03/2020, 8:32 PM
    Is there a way to remove/replace existing methods with a compiler plugin?
    f
    d
    d
    • 4
    • 12
  • j

    jdemeulenaere

    05/04/2020, 7:22 AM
    Is there a way to analyse Kotlin files with the new compiler frontend using the
    kotlin-compiler
    artifact ?
    🇳🇴 1
    d
    • 2
    • 3
  • m

    melatonina

    05/06/2020, 7:29 PM
    I'm writing a compiler plugin with Arrow Meta. I manage to print some debugging output with
    messageCollector?.report(CompilerMessageSeverity.WARNING, message, HERE)
    but using any lower severity level does not produce any output on the console, even if I pass
    -verbose
    as compiler argument. Why? How can I use different severity levels or otherwise print messages to the console from my compiler plugin?
    s
    • 2
    • 1
  • p

    PHondogo

    05/08/2020, 7:56 PM
    Hello! How can I get IrClass of other module from symbol? when I call symbol.owner I got error: java.lang.IllegalStateException: Symbol for ... is unbound
    s
    • 2
    • 6
  • t

    turansky

    05/09/2020, 4:25 PM
    Is it possible to report errors from
    IrGenerationExtension
    ?
    r
    • 2
    • 9
  • p

    PHondogo

    05/10/2020, 9:19 AM
    Hello! In ir transformation phase i need to add private default setter to property if it is not exists (is val). For that case i can assign IrProperty.setter = to needed implementation. But after transformation java still generate final field and throw 'Update to non-static final field ... attempted from a different method (...) than the initializer method <init>' How can i make this work? I check IrProperty class and find out that it has isVar flag that is not correlate with availability of setter method. It is just final field initialized in constructor.
    • 1
    • 1
  • p

    PHondogo

    05/10/2020, 9:53 PM
    I'm using kotlin 1.4-M1 with IR enabled and found out bug in generated code. I want to know is it known bug or I should repot it?
    abstract class TestBase<T> {
            suspend fun test(value: T) {
                println(doTest(value))
            }
    
            protected abstract suspend fun doTest(value: T): T
        }
    
        class TestInherit : TestBase<String>() {
            override suspend fun doTest(value: String): String {
                return value + "/" + value
            }
        }
    
        @Test
        fun test() {
            runBlocking {
                TestInherit().test("aaa") /* throws exception here java.lang.AbstractMethodError: Receiver class TestInherit does not define or inherit an implementation of the resolved method 'abstract java.lang.Object doTest(java.lang.Object, kotlin.coroutines.Continuation)' of abstract class TestBase. */
            }
        }
    If define TestBase without generic it works ok.
    abstract class TestBase {
            suspend fun test(value: String) {
                println(doTest(value))
            }
    
            protected abstract suspend fun doTest(value: String): String
        }
    
        class TestInherit : TestBase() {
            override suspend fun doTest(value: String): String {
                return value + "/" + value
            }
        }
    
        @Test
        fun test() {
            runBlocking {
                TestInherit().test("aaa") // OK
            }
        }
    t
    • 2
    • 2
  • f

    Foso

    05/12/2020, 8:04 PM
    Is it possible to restart the compiler from inside a compiler plugin or just restart the plugin ?
    s
    • 2
    • 2
  • p

    PHondogo

    05/13/2020, 3:20 PM
    When IrField.isStatic == true initializer block is not generated when compiling to JS. Only var fieldName; is generated
    • 1
    • 1
  • p

    PHondogo

    05/14/2020, 9:08 AM
    Is it possible to add synthetic class to package level in SyntheticResolveExtension?
    r
    s
    r
    • 4
    • 6
  • k

    Kiryushin Andrey

    05/15/2020, 10:54 AM
    I observe an interesting type inference behavior regarding
    it
    parameter in lambdas contained in pairs, lists or other data structures. This code sample
    var pair: Pair<Int, (String) -> String> = 2 to { "param $it" }
    var pair2: Pair<Int, (String) -> String> = 2 to { p -> "param $p" }
    
    var list: List<(String) -> String> = listOf { "param $it" }
    var list2: List<(String) -> String> = listOf { p -> "param $p" }
    looks fine to IDE, but fails to compile with the following errors for the lines using
    it
    lambda parameter:
    Type inference failed. Expected type mismatch: inferred type is Pair<Int, () -> String> but Pair<Int, (String) -> String> was expected
    Unresolved reference: it
    Type inference failed. Expected type mismatch: inferred type is List<() -> String> but List<(String) -> String> was expected
    Unresolved reference: it
    But the compiler is happy with the root-level lambda declarations like this
    var func: (String) -> String = { "param $it" }
    var func2: (String) -> String = { p -> "param $p" }
    Is this a bug or an intended behavior? Are there any workarounds that would make the compiler happy and at the same time keep the code neat (that is, using
    it
    but without full lambda type annotations at usage site)? I'm using Kotlin 1.3.71 in multiplatform project and can see this both in JVM and JS targets.
    w
    • 2
    • 9
  • p

    PHondogo

    05/16/2020, 4:26 PM
    Hello! Is there any way to itarate through all class descriptors in module descriptor?
    r
    • 2
    • 7
  • r

    rnett

    05/17/2020, 10:21 PM
    I'm using an IR rewrite pass to replace a property with a new one with the same name, but a new backing field, and accessors that get/set a property of that backing field. This works fine for the most part, but in
    init
    blocks and class methods, references to the property's accessors seem to be replaced with the backing field. Ex:
    class Test(@Watch var x: Int){
        fun print(){
            println("Prop: $x")
        }
    }
    fun main() {
        val t = Test(3)
        
        println(t.x)
        t.print()
    }
    The
    println(t.x)
    works fine and prints 3, but the
    println
    in
    print
    prints the backing field. I'm using 1.4-M1. Ideas? I've dumped the IR and there doesn't seem to be any differences
    p
    • 2
    • 4
  • p

    PHondogo

    05/17/2020, 10:46 PM
    ModuleDescriptor.getSubPackagesOf doesnt return subpackages if there is no .kt files in searched package. Is it a bug or i miss smth. Please advice me.
    • 1
    • 1
  • r

    rnett

    05/18/2020, 3:43 AM
    I'm trying to add a synthetic property to classes w/ my annotation. It works as expected, except it turns any property access statements on that class into get_fields on the added property's backing field. It does this before it even gets to the IR phase, so I'm not sure what's causing it. The SyntheticResolveExtension is just:
    class KlairvoyantResolveExtension() : SyntheticResolveExtension {
        override fun generateSyntheticProperties(thisDescriptor: ClassDescriptor, name: Name, bindingContext: BindingContext, fromSupertypes: ArrayList<PropertyDescriptor>, result: MutableSet<PropertyDescriptor>) {
            if (!thisDescriptor.hasWatchAnnotation())
                return
    
            if(result.any { it.name == Name.identifier(Names.ClassWatcherProp) })
                return
    
            with(FrontendReferencer(thisDescriptor.module)) {
                val classWatcherDescriptor = SimpleSyntheticPropertyDescriptor(thisDescriptor, Names.ClassWatcherProp, KotlinTypeFactory.simpleNotNullType(Annotations.EMPTY, CompositeWatcher, listOf()), visibility = Visibilities.PUBLIC)
                result.add(classWatcherDescriptor)
            }
        }
    }
    s
    • 2
    • 3
  • r

    rnett

    05/19/2020, 1:47 AM
    I'm writing an IDE plugin for my synthetic property, and I'm including my compiler plugin as a dependency and reusing the SyntheticResolveExtension class. However when I run the IDE, it complains that my extension doesn't implement SyntheticResolveExtension. I can use reflection to get the class, and while it has a superinterface of SyntheticResolveExtension, it is not equal to the SyntheticResolveExtension it is checking for. I suspect this comes from mine coming from "org.jetbrains.kotlin:kotlin-compiler-embeddable:1.4-M1", and the IDEs isn't (I can't seem to get the
    runIde
    task to use the 1.4-M1 Kotlin plugin, which may be part of the reason why). Is there a way to make this work without duplicating a bunch of code in the ide plugin?
    t
    • 2
    • 14
  • r

    rnett

    05/19/2020, 3:07 AM
    With my IDE plugin, my field resolves fine once it is typed, but doesn't appear in autocomplete. Is there an extension point I'm missing? I'm using
    generateSyntheticProperties
    in my
    SyntheticResolveExtension
    s
    r
    • 3
    • 13
  • d

    Dominaezzz

    05/19/2020, 5:17 PM
    I manage to get the compiler to spew this.
    e: org.jetbrains.kotlin.codegen.CompilationException: Back-end (JVM) Internal error: Couldn't inline method call 'usingConnection' into
    I can reproduce it in my project but I'm having trouble making a self-contained reproducer. I would publish the project but the contents are personal/sensitive (My access tokens are hard coded). What to do? I fix the error when I stop taking advantage of contracts in suspend methods.
    // Breaks compiler
    val value: String
    withContext(...) {
        value = loadFromDb()
    }
    println(value)
    
    // Doesn't break
    val value: String = withContext(...) {
        loadFromDb()
    }
    println(value)
    • 1
    • 2
  • r

    ralf

    05/20/2020, 2:51 AM
    @shikasd Do you know what exactly triggers this issue? https://youtrack.jetbrains.com/issue/KT-38576 I’m running into it, too. Is it the fact that there’s a mixed Java / Kotlin source set or that the Kotlin class extends a Java class?
    s
    • 2
    • 4
Powered by Linen
Title
r

ralf

05/20/2020, 2:51 AM
@shikasd Do you know what exactly triggers this issue? https://youtrack.jetbrains.com/issue/KT-38576 I’m running into it, too. Is it the fact that there’s a mixed Java / Kotlin source set or that the Kotlin class extends a Java class?
Okay, I can constantly reproduce now. The Java class must be accessed in some way. If just a random Java class would be on the classpath, then it isn’t a problem. Bummer
s

shikasd

05/20/2020, 9:56 AM
@ralf yeah, it is
preciseJavaTracking
that causes that, so you can disable it in gradle or compiler configuration
r

ralf

05/20/2020, 5:12 PM
Yes, I’m disabling this on a module level for now in my corresponding Gradle plugin. It’s unfortunate, though 🙂
s

shikasd

05/20/2020, 5:37 PM
Surely it is We don't have that many mixed modules in our codebase though, so I was experiencing it with kapt only. Taken me some time to catch :D
View count: 4