https://kotlinlang.org logo
Join Slack
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