https://kotlinlang.org logo
Join SlackCommunities
Powered by
# general-advice
  • j

    JasonB

    07/18/2024, 8:19 PM
    question on nested
    use
    blocks: let's say I have a reader and a writer - if I nest the writer's
    use
    inside of the reader's
    use
    , and the reader is empty, will the writer's stream still be closed?
    s
    • 2
    • 4
  • p

    Phil Richardson

    07/26/2024, 7:26 PM
    I am looking at some Java interop stuff. To keep things simple, I am working with a application SDK which is in Java, and it accepts some JSR-223 loaded scripts. The primary target is Groovy script and at the moment. Groovy needs to pass a Closure that is processed essentially as a callback for initialisation reasons. The Groovy is loaded early, but the initialisation happens late - this happens as it is a Spring app, so bean registration needs to happen early, but initialisation occurs only after bean registration. That said, it's not that I dislike Groovy, but let's face it, we are all here because we like Kotlin more, or at a minimum dislike Groovy just a little more than Kotlin 😉 K I don't really have the means to test, but is it one possible, and two what Kotlin & Java types are involved, to be able to pass around some form of Closure like object from Kotlin, that can be invoked Java side? As noted, right now
    groovy.lang.Closure
    is being accepted by Java to allow callback to the script. It does also allow processing of a
    javax.script.Invocable
    . I don't have much control over the SDK - but would certainly try and influence it with justification. So if I wanted to say pass in an instance of a Kotlin function type, i.e. Lambda, anon-function or callable reference. What would be the types that Java needs to handle? Are they different say between a Lambda and callable ref? I know I could just specifically generate an Object that implements Callable, thus knowing the types by default, but that seems like forcing something over using the more natural - and readable - kotlin syntax
  • p

    PHondogo

    07/30/2024, 7:31 PM
    What is expected behavior for loop below (what should be printed)?
    Copy code
    for (v in UByte.MIN_VALUE..UByte.MAX_VALUE) {
        println(v) // it is going after 255 and more. Why?
    }
    e
    k
    • 3
    • 9
  • g

    groostav

    08/02/2024, 12:55 AM
    So im looking for a sparse left join on some data,
    Copy code
    val left = listOf(
        CoolRecord("name1", emptyList()),
        CoolRecord("name2", emptyList()),
        CoolRecord("name3", emptyList())
    )
    val right = listOf(
        CoolRecord("name1", listOf(1.0, 2.0))
        CoolRecord("name3", listOf(5.0, 6.0))
    )
    
    val result = reallySlickJoinFunction(left, right)
    
    assertEquals(result, listOf(
      CoolRecord("name1", listOf(1.0, 2.0)),
      CoolRecord("name2", emptyList()),
      CoolRecord("name3", listOf(5.0, 6.0))
    ))
    anybody got some hints on how i can implement
    reallySlickJoinFunction
    ?
    a
    • 2
    • 1
  • g

    groostav

    08/02/2024, 12:57 AM
    I really want to avoid calling
    right.single { record.name == target }
    , because if
    target
    comes from a loop thats a full cartesian product, and the data sets of left & right could be a thousand or so elements long but they are ordered, so
    right[n]
    must have a record in
    left
    that occurs before
    right[n+1]
    c
    s
    • 3
    • 5
  • h

    Holger Steinhauer [Mod]

    08/08/2024, 10:20 AM
    Hey folks. I have a nice little niche challenge for a not-so-average-project and could use some ideas / hints. I am about to replace a "Access App" for a small group of clients. The challenge: It needs to run completely offline (no internet is available at all) and for a few distributed people working at different locations. At the moment the distributed set up is somehow (I reall don't know how) working with the Access "database" file living on OneDrive or Dropbox. The users explicitely said that a central database server and a VPN connection is not acceptable. For me this bring the challenge to find a file based db backend that can also live on cloud storages like OneDrive. The current userbase might be fine off with sqlite. But I would like to have a solution where the source file isn't locked for one user only. So I am looking for either an alternative to sqlite or a library that handles the "I am locking for the write when needed" / collision detection and solving merge conflicts. ( I think for the use case a pure time based resolution is good enough fttb). Another side-challenge: There is no budget for subscriptions or loads of maintenance work... Looking forward for your input.
    s
    k
    • 3
    • 6
  • a

    Amir H. Ebrahimnezhad

    08/21/2024, 3:11 PM
    Hi everyone, Is there a way to have a variable or class have either the type A or B? I have seen something in Arrow EitherA, B and I wonder if there's something in the language itself too. If that's not possible I have two enum classes that I want to merge the values at some places so either value can be possible.
    s
    • 2
    • 7
  • g

    groostav

    09/18/2024, 8:45 PM
    is there an
    IndentedStringBUilder
    anywhere? I feel like I've bumped into this need a couple times. I want a stringbuilder (or perhalps more simply an
    Appendable
    ) that will auto-insert a prefix for each newline. something like
    Copy code
    val builder = StringBuilder()
    builder.appendLine("preamble {"}
    
    val indented = builder.indent(indent = " ", indentCount = 2) // new reference but mutates same buffer as 'builder'
    
    val multilineOutcodeString = someUserObject.toString()
    indented.appendLine(multilineOutcodeString)
    
    builder.appendLine("}") 
    
    print(builder.toString())
    outputting
    Copy code
    preamble {
      SomeUserObjectThatOutputsManyLines:
      SomeUserObjectExtraLine
      line2
    }
  • a

    Amir H. Ebrahimnezhad

    09/24/2024, 5:27 AM
    I am starting an educational program in science and programming with a team. I want to develop something like 3Blue1Brown Manim package for Kotlin. But for the first step there are several question to be asked: 1. Is there any projects out there doing this job? So that I stay more efficient? 2. I want to introduce vector graphics (which is presumably the right step for having multiple transitions and resolutions available for work.) What packages do this in Kotlin Or should I write from scratch (I have read about javafx but never used it and it seems to be working with pixels instead)? 3. Any idea how to implement LaTeX for these scenes? 4. Is the process of making the video frame by frame (generating actual images) and then putting them all together as a video good?
    c
    j
    • 3
    • 9
  • g

    Gilles Barbier

    10/09/2024, 5:21 PM
    Hi, I have a situation I do not understand - here is the simplified code:
    Copy code
    import kotlinx.coroutines.channels.Channel
    
    class Box<out M>(
        //  ...
    )
    
    interface Transport<S> {
      //  ...
    }
    
    interface Message {
      // ...
    }
    
    fun <T : Message> test(
      consumer: Transport<T>,
      channel: Channel<Box<T>> = Channel()
    ): Channel<Box<T>> {
      return channel
    }
    
    fun main() {
      lateinit var consumer: Transport<out Message> // just to get the right type
      var c = test(consumer)
    }
    Here the IDE (IntelliJ) does not see any issue. But If I ask IntelliJ to provide the type, I got:
    Copy code
    var c: Channel<Box<Message>> = test(consumer)
    But then IntelliJ itself tells me it's wrong and should be:
    Copy code
    var c: Channel<out Box<Message>> = test(consumer)
    At last, for both type, the can not provide it to the
    test
    function - IntelliJ tells me it's not the right type
    Copy code
    val c: Channel<out Box<Message>> = Channel()
    test(consumer, c)
    Any hint would be greatly appreciated!
    c
    • 2
    • 1
  • v

    Varun Sethi

    10/10/2024, 5:17 AM
    hey can someone help me in getting started with multi module architecture I have read the docs but how to setup in studio and be able to structure them
    c
    • 2
    • 1
  • 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
    ?