https://kotlinlang.org logo
Join Slack
Powered by
# general-advice
  • y

    youssef hachicha

    11/07/2024, 7:59 AM
    Should I use Lambdas or Functions?
    f
    c
    • 3
    • 5
  • m

    mbonnin

    11/07/2024, 5:06 PM
    I've been turning this around for a while: there's no Kotlin equivalent to Java static factory functions, right?
    Copy code
    // How do I do this in Kotlin?
    interface Shape {
      int area();
    
      class Square implements Shape {
        // private constructor here
        private Square() {}
        @Override public int area() {return 0;}
      }
    
      // more shapes...
    
      /**
       * static factory method
       * Doesn't work on a Kotlin companion function because the Square constructor is private
       */
      static Square square() {
        return new Square();
      }
    }
    k
    r
    e
    • 4
    • 17
  • b

    Bilagi

    11/10/2024, 8:24 AM
    Hello All, I already know Android development with Kotlin and would like to learn backend development with Kotlin using Spring Boot. Could you recommend some Udemy courses for this?
  • a

    Andrew O'Hara

    11/11/2024, 9:07 PM
    I've run into an issue compiling an expression. I understand why it happened, and how to work around it. I just wonder if there's a better workaround. Given this class:
    Copy code
    class BusinessLogic(
        val getMessage: () -> String
    )
    I want to build a factory method that would let me override
    getMessage
    with some static String.
    Copy code
    fun createBusinessLogic(messageOverride: String? = null): BusinessLogic
    I initially came up with this:
    Copy code
    fun createBusinessLogic(
        messageOverride: String? = null
    ) = BusinessLogic(
        getMessage = if (messageOverride != null) {
            { messageOverride }
        } else {
            val random = Random(1337)
            { "Message ${random.nextInt()}" }
        }
    )
    Which fails to compile, because the compiler thinks the
    () -> String
    I'm trying to return is an argument to the
    Random
    constructor. My workaround was to assign the lambda to a
    val
    , and then return that on the next line.
    Copy code
    fun createBusinessLogic(
        messageOverride: String? = null
    ) = BusinessLogic(
        getMessage = if (messageOverride != null) {
            { messageOverride }
        } else {
            val random = Random(1337)
            val supplier = {
                "Message ${random.nextInt()}"
            }
            supplier
        }
    )
    But it's weird! And ugly! I feel like there should be a better way to do this, without resorting to something drastic like:
    Copy code
    fun createBusinessLogic(
        messageOverride: String? = null
    ) = if (messageOverride != null) {
        BusinessLogic { messageOverride }
    } else {
        val random = Random(1337)
        BusinessLogic { "Message ${random.nextInt()}"}
    }
    Which won't really fly in my real app, because the real-life
    BusinessLogic
    has several more arguments that would be duplicated.
    e
    • 2
    • 4
  • a

    Abhilash Mandaliya

    11/13/2024, 10:47 AM
    Hello members. How do I generate
    serialVersionUID
    for my classes implementing
    Serializable
    ? I found several plugin options or doing it manually but none of the plugins work with the latest version of IDEA? Isn't there any default support like Java?
  • s

    Stylianos Gakis

    11/20/2024, 2:51 PM
    For the upcoming "*Non-public primary constructor is exposed via the generated 'copy()' method of the 'data' class.*" change in the language, what do you think is going to be your go-to solution? I was thinking of providing a manual
    copy()
    function, only with the parameters that I need for each use case which will just create a new instance of the data class, just like the normal
    copy
    function would. Any reasons why I should not be doing that?
    k
    • 2
    • 3
  • g

    Gilles Barbier

    11/21/2024, 8:18 AM
    Hello, I'm building a Kotlin library including a shutdown hook ("Runtime.getRuntime().addShutdownHook(...)"). When I run it from IntelliJ within a main() Kotlin app, the hook works as expected. When I run it from IntelliJ within a minimalist Main Java app, the hook does not work. Would you have any hint why ?
  • j

    juliocbcotta

    12/04/2024, 12:28 PM
    Maybe someone here can help https://kotlinlang.slack.com/archives/C0B8M7BUY/p1733219925941219
  • n

    Norbi

    12/25/2024, 6:15 PM
    Hello, Is it legal to own a kotlin.xy domain name and use it for a Kotlin-related commercial product's or service's site? Thanks.
    c
    • 2
    • 4
  • g

    groostav

    01/19/2025, 7:33 AM
    so I'm in this funny spot where im removing a massively overbuilt antlr thing with what im hoping will be a hundred lines of hand written parser for a CSV file. Is there an iconic kotlin tokenizer implementation? I was kinda hoping I could implement something really simple with
    Scanner
    , but it demands delimeters that I dont want to give it. I was also hoping kotli might have a kind of reader + regex extension function, something like
    <http://java.io|java.io>.Reader.takeWhile(regex: Regex)
    , but no luck there either. What does a quintessential kotlin text tokenizer look like?
    a
    k
    • 3
    • 9
  • a

    Abhilash Mandaliya

    01/24/2025, 6:40 AM
    Hello guys, I suddenly started getting this error without any change in my project:
    Copy code
    sairaham@kotlin-dev-ThinkPad-P53:~/workspace/kotlin-dev-connect$ ./gradlew build -x test
    Starting a Gradle Daemon (subsequent builds will be faster)
    
    FAILURE: Build failed with an exception.
    
    * Where:
    Build file '/home/sairaham/workspace/kotlin-dev-connect/build.gradle.kts' line: 57
    
    * What went wrong:
    Class org.jetbrains.kotlin.cli.common.CompilerSystemProperties does not have member field 'org.jetbrains.kotlin.cli.common.CompilerSystemProperties COMPILE_INCREMENTAL_WITH_ARTIFACT_TRANSFORM'
    
    * Try:
    > Run with --stacktrace option to get the stack trace.
    > Run with --info or --debug option to get more log output.
    > Run with --scan to get full insights.
    > Get more help at <https://help.gradle.org>.
    
    BUILD FAILED in 6s
    5 actionable tasks: 1 executed, 4 up-to-date
    I have no clue what is wrong here. Google search also didn't help with it. Any help is greatly appreciated 🙏
    c
    • 2
    • 3
  • a

    Andrew O'Hara

    02/03/2025, 5:07 PM
    For the times you're forced to work with SOAP, I'm curious what strategies people use. We've tried a few to varying degrees of success: • generate JEE adapters from the WSDL using some EOL JDK 8 binary • map the entire structure with jackson XML bindings • navigate the XML DOM for reads, and use document templates for writes Does anyone know of any other methods? Perhaps a relatively modern library to handle the boilerplate?
  • e

    Eugen Mayer

    02/07/2025, 9:00 AM
    Hello! Asking myself, how expensive a toMutableList() actually is. Looked down the implementation, in the end goes for toArray() which will do a copy using the system (C) based implementation using System.arraycopy. But in the end, the actual elements are, AFAICS, not copied but assigned by ref. So i see that it is a O(n) runtime, but it will not copy the actual values (space) but use the ref - maybe even better depending of possible pointer arr in System.arraycopy. Even though i found https://slack-chats.kotlinlang.org/t/455570/how-expensive-is-mutablelist-tolist-is-it-just-basically-a-t i would love to have a more technical answer to that. Motivation: Due java op, we get a List and have no idea if it is mutable or not, but we want to have a mutable list. Usually (currently), it already is a mutable list, but it might change. So we though about using toMutableList 'to ensure it'.
    k
    • 2
    • 1
  • s

    Slackbot

    02/10/2025, 10:40 AM
    This message was deleted.
    c
    • 2
    • 1
  • c

    Caleb B

    02/24/2025, 3:58 PM
    Is there any way to "pin" generics to another type? Like have a
    Map<Class<T>, Supplier<T>>
    , where
    T
    is NOT a type parameter of the enclosing class but instead "pinning" the type of the supplier to the type of the class for runtime type validation? Instead of
    Map<Class<*>, Supplier<*>>
    and having to suppress constant type coercion warnings
    s
    • 2
    • 5
  • r

    Raj Paliwal

    02/28/2025, 5:40 PM
    Hello everyone, I am facing an issue where my app is being killed, and in the Exit Information, I see the following details: • Reason:
    OTHER_REASON
    • Description:
    ScreenOffCheckKill 26m3s4ms (26.33344%) threshold 2.0%
    The issue occurs when a*fter screen turns off, app in background.* The description in the exit logs suggests ScreenOffCheckKill, but I couldn’t find any official documentation explaining this behavior. • What exactly does
    ScreenOffCheckKill
    mean, and why does it happen? • Is this a system-level restriction or a configurable setting? • How can I prevent my app from getting killed due to this reason? • Any pointers to official documentation or similar cases would be highly appreciated. Thanks in advance for any insights!
    c
    • 2
    • 1
  • a

    Amir H. Ebrahimnezhad

    03/20/2025, 3:12 PM
    I'm struggling to publish my library on maven central repository. I use Kotlin and Gradle. Does anyone have new experience regarding this? and possibly give me instructions?
    c
    a
    • 3
    • 21
  • a

    Amir H. Ebrahimnezhad

    04/04/2025, 6:17 PM
    What's the difference between github publish maven and maven itself? I've published something on github and It cannot be found on maven server... although it seems to be published alright.
  • s

    Sebastian Schuberth

    04/05/2025, 8:16 PM
    Anyone knows whether there's a tool that can detect the issue https://www.jetbrains.com/help/inspectopedia/resource.html (unclosed
    AutoClosables
    ) but for Kotlin code and
    use
    ?
  • c

    christophsturm

    05/25/2025, 6:38 PM
    is there going to be a beta release soon that contains the new error handling?
    c
    • 2
    • 1
  • c

    Caleb B

    05/28/2025, 9:06 PM
    I'm making a tiny DSL wrapping an existing builder for a JSON deserializer library, basically adding a few macros to try to make it more declarative. I'm having trouble enabling the bundle of extension methods in the DSL block cleanly. When you're using your own builder class with a
    MyBuilder.() -> Unit
    parameter, you can obviously have the extensions be members of the builder class to be implicitly available, but I can't figure out how to do that with someone else's without making the end user either import them manually or use a
    with
    block like below. Does anyone know how I could implicitly let people use this bundle of extensions in the DSL without the
    with
    block? [Comment = original builder, code = my WIP syntax]
    c
    • 2
    • 4
  • c

    Caleb B

    06/11/2025, 8:27 PM
    Is there a way to easily make multiple names for a single function without having to redeclare them entirely? Mainly for DSL/operator purposes. For example:
    Copy code
    fun foo(arg1: String, arg2: String) {
      // ...
    }
    
    // Known:
    fun bar(arg1: String, arg2: String) = foo(arg1, arg2)
    
    // Ideal?
    fun bar = foo
    s
    • 2
    • 1
  • c

    Caleb B

    06/11/2025, 8:58 PM
    And another question: Is there any way to let a property setter accept multiple types? Again for DSL stuff. This would be so much easier if we could just make Rust-like macros, lol
    Copy code
    val default: Int
      set(value: Int) { field = value }
      set(value: IntSupplier) { field = value.get() }
    
    // so this can happen:
    mybuilder {
      // either this:
      default = 10
      // or this:
      default = { longOperationToFetchDefault() }
    }
    a
    • 2
    • 1
  • a

    aishwaryabhishek3

    06/25/2025, 6:35 AM
    Hi Folks, I wanted advice regarding structuring a sealed class hierarchy with generics, Lets say I have a sealed class with 2 child classes and one of them needs to be generic, should I make the parent class also generic or only the child class as generic. Basically which one is preferred ->
    Copy code
    // Sealed class without generics
    sealed class Result
    
    // Subclass with a generic type
    data class Success<T>(val data: T) : Result()
    
    // Subclass without a generic type
    object Loading : Result()
    Or
    Copy code
    sealed class Result<T>
    
    class Success<T>(val data: T) : Result<T>()
    
    // Some other subclass that doesn't need T can be defined as
    class Error(val message: String) : Result<Nothing>()
    j
    • 2
    • 1
  • m

    Manuel Lorenzo

    07/09/2025, 1:40 PM
    hello! I'm creating a new app and I want to use RevenueCat paywalls. However I need to facilitate Google Play store a way to test the whole app, bypassing the paywalls and I'm not sure how to do this 🤔
  • c

    Caleb B

    07/09/2025, 11:55 PM
    Is there a way to make an operator function that accepts varargs? For DSL purposes, obviously. Specifically: something like
    "foo" in ("bar", "baz", "qux")
    instead of
    "foo" in listOf("bar, "baz", "qux")
    so it doesn't read as cluttered. This one might actually be impossible since it would require
    fun (vararg T).contains
    , but it would be nice to do
    myList -= "x", "y", "z"
    c
    • 2
    • 2
  • c

    Caleb B

    07/10/2025, 12:01 AM
    Second question: I know there's a way to override the assignment operator (
    =
    ) with kotlin-assignment-plugin, but is there a way to do the same for
    is
    ? I love making DSLs. It's so much fun to screw with the language to make code more readable.
    c
    • 2
    • 1
  • k

    Kev

    08/03/2025, 7:57 AM
    Is there a way for this to know that
    decision.first
    is a
    DecisionResult.Next
    without a manual class? Its not getting inferred for some reason.
    e
    • 2
    • 2
  • a

    Amir H. Ebrahimnezhad

    08/10/2025, 4:49 PM
    I'm making a series of tutorials on Kotlin and I decided to make a fun thumbnail. As a prototype I've used Ai to make concepts and I was drawn to make a Doom style Kodee. Is drawing something like this legal?
  • g

    GeorgeS-Litesoft

    08/20/2025, 5:59 PM
    Is Kotlinlang closed to new members? Is there a process to invite new members?
    s
    g
    • 3
    • 2