https://kotlinlang.org logo
Join Slack
Channels
announcements
100daysofcode
100daysofkotlin
100daysofkotlin-2021
advent-of-code
aem
ai
akkurate
alexa
algeria
algolialibraries
amper
amsterdam
android
android-architecture
android-databinding
androidgithubprojects
android-studio
androidthings
androidx
androidx-xprocessing
anime
anko
apollo-kotlin
appintro
appyx
arabic
argentina
arkenv
arksemdevteam
armenia
arrow
arrow-contributors
arrow-meta
ass
atlanta
atm17
atrium
austin
australia
austria
awesome-kotlin
aws-sdk
ballast
bangladesh
barcelona
bayarea
bazel
beepiz-libraries
belgium
benchmarks
berlin
big-data
books
boston
brazil
brikk
budapest
build
build-tools
bulgaria
bydgoszcz
cambodia
canada
carrat
carrat-dev
carrat-feed
chennai
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
competitivecoding
competitive-programming
compiler
compose
compose-android
compose-desktop
compose-destinations
compose-hiring
compose-ios
compose-mp
compose-ui-showcase
compose-wear
compose-web
confetti
connect-audit-events
corda
cork
coroutines
couchbase
coursera
croatia
cryptography
cscenter-course-2016
cucumber-bdd
cup-presentations
cyprus
czech
dagger
data2viz
databinding
datascience
dckotlin
debugging
decompose
decouple
denmark
dependency-injection
deprecated
detekt
detekt-hint
dev-core
dfw
docs-revamped
dokka
domain-driven-design
doodle
dsl
dublin
dutch
eap
eclipse
ecuador
edinburgh
education
effectivekotlin
effective-kotlin
emacs
embedded-kotlin
estatik
event21-community-content
events
exposed
failgood
fb-internal-demo
feed
firebase
fleet
flow
flowmvi
fluid-libraries
forkhandles
forum
fosdem
fp-in-kotlin
framework-elide
freenode
french
fritz2
fuchsia
fun-adaptive
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
gsoc-compose-multiplatform-storybook
gsoc-ij-gradle-plugin
gsoc-kmp-bazel
gsoc-kmp-bazel
gsoc-kmp-gemini-firebase
gsoc-kotlin-bom-bazel
gsoc-kotlin-lsp-project
gsoc-kotlin-openrewrite
gsoc-wasm-incremental-compilation
gui
hackathons
hamburg
hamkrest
helios
helsinki
hexagon
hibernate
hikari-cp
hire-me
hiring
hiring-french
hongkong
hoplite
http4k
hungary
hyderabad
image-processing
india
indonesia
inkremental
intellij
intellij-plugins
intellij-tricks
internships
introduce-yourself
io
ios
iran
israel
istanbulcoders
italian
j2k
jackson-kotlin
jadx
japanese
jasync-sql
javadevelopers
javafx
javalin
javascript
java-to-kotlin-refactoring
jdbi
jewel
jhipster-kotlin
jobsworldwide
jpa
jshdq
juul-libraries
jvm
jvm-ir-backend-feedback
jxadapter
k2-adopters
kaal
kafka
kakao
kalasim
kapt
karachi
karg
karlsruhe
kash_shell
kaskade
kbuild
kdbc
kgen-doc-tools
kgraphql
kilua
kinta
klaxon
klibs-io
klock
kloudformation
kmdc
kmm-español
kmongo
knbt
knote
koalaql
koans
kobalt
kobweb
kodein
kodex
kohesive
koin
koin-contributors
komapper
kondor-json
kong
konsist
konsist-dev
kontent
kontributors
koog-agentic-framework
korau
kore
korean
korge
korim
korio
korlibs
korte
kotest
kotest-contributors
kotless
kotlick
kotlinacademy
kotlin-asia
kotlin-beam
kotlinbot
kotlin-by-example
kotlinconf
kotlin-csv
kotlin-data-storage
kotlindl
kotlinforbeginners
kotlin-foundation
kotlin-fuel
kotlingforbeginners
kotlin-in-action
kotlin-inject
kotlin-kinetics
kotlin-latam
kotlin-logging
kotlinlondon
kotlinmad
kotlin-multiplatform-contest
kotlin-mumbai
kotlin-native
kotlin-pakistan
kotlin-plugin
kotlinprogrammers
kotlin-pune
kotlin-roadmap
kotlin-samples
kotlin-sap
kotlin-serbia
kotlin-spark
kotlinsu
kotlin-szeged
kotlintest
kotlintest-devs
kotlintlv
kotlinultimatechallenge
kotlin-website
kotlinx-collections-immutable
kotlinx-datetime
kotlinx-files
kotlinx-html
kotlinx-rpc
kotools
kotrix
kotson
kotzilla-platform
kovenant
kprompt
kraph
krawler
kroto-plus
ksp
kstatemachine
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
lincheck
linenbot
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
newname
new-zealand
nigeria
nodejs
norway
npm-publish
nyc
oceania
ohio-kotlin-users
oldenburg
olpaka
oolong
opensavvy
opensource
orbit-mvi
osgi
otpisani
package-search
pakistan
panamá
parameterize
pattern-matching
pbandk
pdx
peru
philippines
phoenix
pinoy
pocketgitclient
polish
popkorn
portugal
power-assert
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
store
storyboard
storytale
strife-discord-lib
strikt
students
stuttgart
sudan
supabase-kt
swagger-gradle-codegen
swarm
sweden
swift-export
swing
swiss-user-group
switzerland
talking-kotlin
tallinn
tampa
teamcity
tegal
tempe
tensorflow
terminal
terpal
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
vilnius-kug
vim
vkug
vuejs
webassembly
web-mpp
webrtc
wimix_sentry
wwdc
zircon
Powered by
# java-to-kotlin-refactoring
  • m

    Marcus Brito

    10/20/2021, 8:34 PM
    from aer.io at any rate
  • d

    dmcg

    10/20/2021, 8:34 PM
    Good question. I don’t think that it is, because when I asked them where we could get a PDF version (my favourite, because the syntax highlighting is in colour and the links into the repo work) they said that https://www.ebooks.com/en-us/book/210356108/java-to-kotlin/duncan-mcgregor/ is the place
  • d

    dmcg

    10/20/2021, 8:35 PM
    And when I say we, I mean the public, because Nat and I already have the PDF version 😉
  • m

    Marcus Brito

    10/20/2021, 8:35 PM
    of course 🙂
  • m

    Marcus Brito

    10/20/2021, 8:38 PM
    awesome, got my pdf 🎉
    🎉 1
  • d

    dmcg

    10/21/2021, 7:53 AM
    If you like it, then we’d be very grateful if you would leave a review on Amazon, as we don’t have many there. Please be honest - we’d rather that people read the book for the right reasons
    👍 2
    p
    • 2
    • 2
  • p

    Piotr Krzemiński

    11/05/2021, 8:43 AM
    hi Duncan, Nat! I'm just starting reading the book and so far I really like it. One question: I found a place where stuff can be simplified - page 18 in paperback, adding Kotlin plugin: we don't have to add the
    stdlib
    explicitly, it's added by default. I wanted to report an errata via O'reilly, but formally it's not an error, just an idea for simplification showing that onboarding Kotlin is even simpler. Is this channel a good place for such suggestions?
    👍 1
    n
    • 2
    • 7
  • p

    Piotr Krzemiński

    11/08/2021, 1:31 PM
    here's an interesting topic: mutable data classes 🙂 Duncan and Nat claim that it's unsafe with respect to
    equals
    and
    hashCode
    , and it's actually great point - I've never looked at it this way, maybe because I create deeply immutable data classes (unless I refactor some JavaBeans-style code, I leave `var`s temporarily) IMO IntelliJ should add a warning/inspection, like it's done for e.g. using
    Optional
    for class fields. The goal still being able to create a concise, kotlinic version of a JavaBean, but not pretending that it's fine 🙂 .WDYT?
    d
    n
    • 3
    • 7
  • p

    Philipp Mayer

    03/28/2022, 7:01 PM
    Out of curiosity: What is the guideline on naming files either starting with upper or lowercase? I just saw it in Duncan's videos and couldn't find a reference to it in the book.
    j
    d
    c
    • 4
    • 18
  • p

    Philipp Mayer

    03/29/2022, 9:00 AM
    While we’re talking about package and file design: Am I the only one missing package privacy? I can somehow understand why they dislike it, but always creating a new module feels like quite a burden for a mid-sized app. How are you tackling that? Creating modules? Or simply don’t care about having everything public? 🤔
    d
    n
    • 3
    • 2
  • w

    Wesley Hartford

    05/05/2022, 7:43 PM
    Java's
    Map.computeIfAbsent()
    function documentation includes:
    Copy code
    If the mapping function returns {@code null}, no mapping is recorded.
    However, when calling this function from Kotlin code, the mapping function has a signature
    (K) -> V
    , meaning that the passed in function cannot return
    null
    . Is there any way to use
    computeIfAbsent
    from kotlin passing a function which may return
    null
    ?
    k
    j
    d
    • 4
    • 8
  • k

    Kev

    11/17/2023, 6:05 AM
    I’m busy looking at the API for
    kotlin.collections.List
    interface. Does anyone know where I can find the implementation of this interface?
  • n

    natpryce

    11/17/2023, 12:00 PM
    If you click on the typename List and type Command-H, IntelliJ will show the hierarchy of sub-interfaces and implementations of the List interface
  • n

    natpryce

    11/17/2023, 12:01 PM
    However … kotlin.collections.List is treated specially by the compiler on the JVM platform, and mapped to the java.util.List type. So most of the subclasses you will see in the hierarchy panel will be Java classes that implement java.util.List, such as java.util.ArrayList.
    k
    • 2
    • 1
  • j

    Jose Ramon (JR)

    12/02/2023, 11:35 PM
    @natpryce, where can I buy the book in both digital and paperback format, like Manning does ?
  • d

    dmcg

    12/08/2023, 8:15 PM
    Unfortunately not a thing that O’Reilly offer
  • d

    dmcg

    12/08/2023, 8:17 PM
    You can get a DRM-free PDF from https://www.ebooks.com/en-gb/book/210356108/java-to-kotlin/duncan-mcgregor/
    j
    • 2
    • 2
  • d

    Darryl Miles

    12/16/2023, 4:55 PM
    Hello, I am using the JPA NoArg gradle plugin, is there a similar plugin (or options) to use on an EJB project, I would like to annotate the Kotlin class and have it provide the "open" keyword for the "class" and any non-private methods, including generated standard getters/setters, Thanks
    k
    • 2
    • 2
  • d

    Darryl Miles

    12/16/2023, 4:57 PM
    This is the JPA plugin that manages the NoArg https://plugins.gradle.org/plugin/org.jetbrains.kotlin.plugin.jpa I am happy to write a new / custom plugin if needed, just need to understand an outline of how to modify the methods to implicitly add "open" when the class is annotated with a customer annotation like
    kotlin('plugin.jpa')
    already provides for JPA
  • d

    Darryl Miles

    12/16/2023, 4:58 PM
    I would then enchance this plugin to automatically looks for JavaEE related annotations on classes (such as jakarta.ejb.* like Stateless/Stateful/Startup/Singleton/etc...) to provide automatic detection and modification in this area
  • d

    Darryl Miles

    12/17/2023, 11:33 AM
    On the same theme use of the idiom `@SomethingLikeInject private lateinit var fieldName: FieldType`` is there a JPA/JavaEE aware build time plugin to check all uses of
    lateinit
    to confirm they have an expected injection annotation on the field, and maybe warn if the field is left public. Maybe there is also the ability to put the plugin in debug build mode and it will insert implicit call to assertion check of all
    lateinit
    at runtime maybe at the end of all constructors such as
    constructor() { myBusinessLogicMethodCall();  injectedKotlinLateInitInjectionChecker() }
    and a method inserted like
    private fun injectedKotlinLateInitInjectionChecker() {  assert((FieldType?)fieldName != null) {"injected Kotlin lateinit usage check failed on field: fieldName"} }
    t
    • 2
    • 2
  • d

    Darryl Miles

    03/03/2024, 5:26 AM
    Trying to recover validation-api annotations from JPA entites in Kotlin however it appears the CLASS level annotations are in the expected place But the column/field/member/accessor-property-method annotations are in some other (secret/hidden) place like:
    Copy code
    val kclass = MyEntity::class
    val randomMember = kclass.members.findLast { it.name == "randomProperty" }  // KCallable<*>
    val kmutable = if(randomMember is KMutableProperty) randomMember as KMutableProperty else null  // KMutableProperty is the real type
    val javaField = kmutable?.annotations  // this is the only non-empty annotations field/member/method/property that exists around "randomProperty"
  • d

    Darryl Miles

    03/03/2024, 5:27 AM
    This "javaField" (kotlin.reflect.jvm.javaField) does not seem to be public API but it has a non-zero byte array content visible in debugger
  • d

    Darryl Miles

    03/03/2024, 5:29 AM
    Is there a more sane way to get hold of the annotation from
    @jakarta.validation.constraints.Size(max = 123) open var randomProperty: String? = null
  • d

    Darryl Miles

    05/16/2024, 7:37 PM
    I am using Kotlin with EJBs, and using the @KotlinAllOpenClass annotation, however I can not use the
    private
    keyword on a method, because it seems Kotlin will make it
    static
    or
    final
    and use of
    private open fun methodName()
    is invalid use of
    open
    keyword. However it seems it is not advised to
    final
    the method due to the proxy nature of EJB application server, because many facets are injected/provided so the container needs to be free to perform interception/injection of anything it sees fit to manage EE requirements. Is there a solution, is this a bug with
    kotlin("plugin.allopen")
    not understanding the full requirements ? Thanks
  • d

    Darryl Miles

    05/16/2024, 7:40 PM
    Currently I am having to do
    Copy code
    /** private **/ fun methodName()
    to at least document the programmers intention, even if the language forcing something else.
    • 1
    • 1
  • n

    natpryce

    05/17/2024, 10:54 AM
    You are probably better off asking in the #server channel
    👍 1
  • w

    Wesley Hartford

    06/12/2024, 4:08 PM
    This is more of an interop question than refactoring, but I couldn't find a more appropriate channel: I'm working on a Kotlin class which implements a Java interface. One of the methods in the Java interface has parameters annotated with
    @Nonnull
    . Kotlin knows that my implementing function should have non-null types for those parameters. The only problem is, the Java code which calls the interface passes
    null
    for these
    @Nonnull
    annotated parameters. Kotlin, of course, throws an exception when
    null
    is passed to a non-null type. I'd like to change the signature of my function to have nullable types, but then Kotlin tells me that its no longer implementing the function it should be. Is there any way to tell Kotlin to ignore the annotations on that method or the specific parameters? I've filed a bug report with the maintainer of the interface, but I'd like to move forward before the fix is released.
    k
    k
    • 3
    • 6
  • d

    Darryl Miles

    12/02/2024, 12:16 PM
    How can you describe
    MyType[].class
    in kotlin ?
    MyType::class.java.arrayType()
    does not seem to be it, I get [UNRESOLVED_REFERENCE] back. Code snippet looks like:
    Copy code
    class MyType<T> {
      val targetClass: Class<T>
      val isArrayType: Boolean
      constructor(targetClass: Class<T>, isArrayType: Boolean = false) {
        this.targetClass = targetClass
        this.isArrayType = isArrayType
      }
      fun toTypeForJackson(): Class<*> {
        return if(isArrayType) targetClass.arrayType() else targetClass   /// <<< ERROR HERE
        // tried also: targetClass.arrayType()::class.java
      }
    }
    Java code that compiles:
    Copy code
    public class MyUtil {
      public static <T> Class<?> foo(Class<T> targetClass, boolean isArrayType) {
        if(isArrayType)
          return targetClass.arrayType();
        else
          return targetClass;
      }
    }
    Just testing it works as expected, maybe I make a Java library project with this util method to resolve ? UPDATE: Doh! so Class#arrayType() came with JDK12 and project targets JDK11 as it is a library project, while runtime testing is JDK21. Solution
    java.lang.reflect.Array.newInstance(targetClass, 0)::class.java
  • s

    Svatopluk Šimara

    04/06/2025, 5:17 AM
    Hi, the IntelliJ button - convert to Kotlin works great, but leaves some things I'd love to automatize. Do You know a tool that uses AST, and can convert following code?
    "Hello, %s".formatted(name)
    ->
    "Hello, %s".format(name)
    I'm not looking for regexs, I tried Kotlin complier API - with some chatgpt promps, but I keep having troubles converting even such simple code - I can parse it, find the relevent method, but not replace it 😕 Basically I'm looking for something like https://errorprone.info/docs/refaster - a tool that allows automated refactorings OR a piece of code where is the Kotlin compiler setup correctly 🙂 My trouble isn't just
    formatted
    - I have 500K LOC project, and I want to resolve all problems at once
    ✅ 1
    j
    n
    • 3
    • 3