/r/Kotlin

Photograph via snooOG

Discussion about Kotlin, a statically typed programming language for the JVM, Android, JavaScript, and native.

Kotlin is a statically typed programming language for the JVM, Android, JavaScript, and native.

Subreddit rules:

  1. Be civil
  2. No spam
  3. Stay on-topic
  4. No fluff

Related subreddits:

Resources:

/r/Kotlin

87,240 Subscribers

0

Kotlin poem

Suspend my heart in coroutines of light While loops of stars dance through the night Nullable dreams may fade to none Until our Boolean day is done

Companion objects walk beside In private spaces where we hide Mutable lists of memories flow Through init blocks of long ago

Lambda expressions touch the sky As functions higher still may fly Our sealed classes hold us tight In data structures of delight

Override shadows of the past With open classes built to last Var by var we change and grow Through interfaces high and low

1 Comment
2024/11/03
09:55 UTC

4

Cronjob in Kotlin using Ktor

Hello fellows, How could I execute cronjobs/job scheduler in kotlin using ktor? I have a cluster setup with kubernetes, which means i need to execute the job only once regularly having multiple servers

What could you recommend here?

Thanks in advance!

4 Comments
2024/11/03
01:23 UTC

3

Algebraic Data Types In Kotlin

0 Comments
2024/11/03
00:02 UTC

6

KWeb is dead 😭 what framework should I switch to?

Here's the situation:

I have a large project that is mostly a KMP client side app. But I have a smaller server component, which has an even smaller web interface.

I really want to keep the web side of things simple, so I don't have to install node or webpack as part of my build environment.

I also loved that KWeb was just all pure Kotlin. As the majority of the work I'm doing is in kotlin, it was really nice for context switching. But I realize that may not be possible.

The core of the server, the rest API is in Ktor, and I want to keep that. KWeb just slotted in as extra routes. So something that can coexist with other routes inside of Ktor is pretty much a must.

So what are my options, anyone have a particular favorite?

Thanks in advance!

5 Comments
2024/11/02
20:20 UTC

8

🚀 [Announcement] FleekSoft IO: Lightweight JDK I/O Classes for Kotlin Multiplatform! 🌐

We’re thrilled to share our latest creation: FleekSoft IO! It’s a lightweight library designed to bring all the familiar Java I/O goodness—like Reader, InputStream, BufferedReader, and more—to Kotlin Multiplatform. If you’ve ever wanted an easier way to handle streams and character data across multiple platforms, you’ll want to check this out! 😄

What FleekSoft IO Brings to the Table:

• A Port of JDK I/O Classes: We’ve carefully ported essential JDK classes so they work seamlessly with Kotlin Multiplatform. Same API you’re used to, but now for Android, iOS, and beyond!

• Charset Support: Built-in support for character encoding/decoding with Charset, making text handling a breeze.

• Consistent API: One codebase, one API, everywhere.

Why We Built It:

We wanted to simplify cross-platform development by making I/O operations as straightforward in Kotlin as they are in Java. No more looking for clunky workarounds—just familiar, clean APIs that work wherever your project takes you.

Check out it at Github: https://github.com/fleeksoft/fleeksoft-io

7 Comments
2024/11/02
13:06 UTC

17

Kotlin Multiplatform Charset v0.0.1 - A Pure Port of JDK Charset for Cross-Platform Encoding & Decoding!

I’m excited to share the first release of Kotlin Multiplatform Charset v0.0.1, a library I’ve developed to bring seamless character encoding and decoding to Kotlin Multiplatform projects. This is a pure port of JDK Charset, so if you’re familiar with Java’s Charset API, you’ll feel right at home!

What’s This Library About?

The library supports both standard and extended character sets and works flawlessly across platforms: JVM, Android, iOS, macOS, Linux, Windows, JavaScript, and WebAssembly. The API is simple and intuitive, making character handling easier in your cross-platform projects.

Key Features

• charset module: For handling standard charsets.

• charset-ext module: Adds support for extended charsets.

• Fully compatible with Kotlin Multiplatform, making it a breeze to work with character sets across different environments.

checkout at: https://github.com/fleeksoft/charset

4 Comments
2024/11/02
13:01 UTC

0

Suggest me a course for android developement and kotlin

same as title

1 Comment
2024/11/02
09:59 UTC

2

Question about Java Libraries

Hey everyone. I have a question about creating Java libraries.

I’ve writte a Java “library” that runs as a fully functioning server, but the idea is that other “clients” would import this library into their code to run as a server on a separate port and integrate alongside their running apps.

However, I’ve run into an issue where when my clients import my “library”, they are met with missing import errors if they are not using the same dependencies and, if they are, there is version mismatches.

How can I fix this so that anyone can import my library and not have clashes? I’m using gradle and have all my dependencies as implementation dependencies. Should I be exposing my server (ktor) dependencies as api?

I thought having them as implementation would bundle them in my client lib so that the methods can be used, but protect them from being used by others, but maybe I am mistaken…

5 Comments
2024/11/01
22:12 UTC

0

Choosing the right programming language

Hi everyone,
i'm developing an API, I've already write 5000 lines in Kotlin and i'm not sure if Kotlin is enough for my necessity, I thought of two options: the first one is to continue my code in Kotlin but I may have problems in the future due to the weight and slowness of the code, another option is to rewrite my code in Rust, but it will take a lot more time because is a lot more difficult.
What you guys think i need to do?
Do you have any tips?

16 Comments
2024/11/01
20:59 UTC

3

Is this a good course to learn springboot dev with Kotlin

Hi everyone. I have done a couple project in Kotlin but never used spring boot in the past. I hear that its a opinionated framework and was wondering if folks here could suggest me a good source to explore springboot dev with Kotlin. I came across this course and wondered if someone in this community knows if it is worth it?

Udemy Course Link

3 Comments
2024/11/01
17:53 UTC

17

Groovy to Kotlin - Migrating a Gradle Build

I created the TDD Gilded Rose codebase in 2021, when the default for Gradle build scripts was the Groovy language. Since then I’ve tried to convert to the Kotlin DSL at least 3 times, and every time I’ve been beaten by some difficulty that just made the conversion uneconomic.

Whatever you think about them, LLMs are certainly changing software economics at a rapid pace, so let’s have another go, this time with AI Assistance.

In this episode

  • 00:00:32 Gradle's guide to migration
  • 00:01:42 Enter AI Assistant
  • 00:02:52 The result doesn't compile, so let's go and fix things
  • 00:05:32 Are vals and ext equivalent?
  • 00:05:55 Now we just have issues with the jOOQ plugin
  • 00:07:01 Pull syntax over from the plugin documentation
  • 00:09:38 Syntax highlighting works, when there are no syntax errors
  • 00:09:53 Now it compiles we can check it works
  • 00:10:41 Can we remove some of the syntax that we have added?
  • 00:11:11 Import quick fix fails and then crashes
  • 00:12:12 Operator fun invoke allows us to prepend a block to an expression
  • 00:13:06 Invoke quick fix not working in the script
  • 00:13:48 Gah another crash
  • 00:14:35 AI Assistant for migrating compiler options
  • 00:15:17 Before vs After
  • 00:16:03 Future Duncan prefers Claud
  • 00:17:29 Wrap up

There is a playlist of TDD Gilded Rose episodes - https://www.youtube.com/playlist?list=PL1ssMPpyqocg2D_8mgIbcnQGxCPI2_fpA

The codebase is available on GitHub https://github.com/dmcg/gilded-rose-tdd

I get lots of questions about the test progress bar. It was written by the inimitable @dmitrykandalov. To use it install his Liveplugin (https://plugins.jetbrains.com/plugin/7282-liveplugin) and then this gist https://gist.github.com/dmcg/1f56ac398ef033c6b62c82824a15894b

If you like this video, you’ll probably like my book Java to Kotlin, A Refactoring Guidebook (http://java-to-kotlin.dev). It's about far more than just the syntax differences between the languages - it shows how to upgrade your thinking to a more functional style.

0 Comments
2024/11/01
13:44 UTC

11

[RELEASE] Ksoup 0.2.0 – Kotlin Multiplatform Library for HTML & XML Parsing

Excited to share that Ksoup 0.2.0 is now live! 🎉 This release brings essential improvements and platform expansions to make HTML and XML parsing more efficient and versatile across Kotlin environments.

🔑 Key Highlights:

• Android Empty Document Fix (#96) - Resolves empty document errors in Android when used with network libraries

• New Platform Support - Now includes WatchOS compatibility (#90)

• Metadata Parsing Improvement - Added shortcut icon parsing to metadata (#89)

• JS Unpacking - Enhances cross-platform integration with JS unpacking (#86)

🔄 Upgrades for Performance and Compatibility:

• Kotlin updated to 2.0.21

• Ktor upgraded to 3.0.1

• Gradle now at 10.7.2

• Android Enhancements: Target SDK 35, AGP 8.7.1, with backward compatibility for older versions

Check it out at: https://github.com/fleeksoft/ksoup

0 Comments
2024/10/31
23:58 UTC

1

Circular References in DB with Ktorm

So I’m running into a potential issue with Ktorm and I want to know if it will be an issue and what the best way to solve it is. I can’t change anything about the database design, so just bear with me on this. I have two SQL tables, let’s call them Users and UserProfiles. These tables were made such that u_userID in the Users table is a primary key and also a foreign key to UserProfiles. Additionally, up_userID in the UserProfiles table is a primary key and a foreign key to Users, creating a bidirectional relationship. If I wanted to preserve this bidirectional relationship using Ktorm, this would cause a circular reference in the entities/tables and because Ktorm eager loads by default should cause a stack overflow error (I’m pretty sure). My question is, does Ktorm natively handle this situation (no stack overflow error) and if not, is there any way to get around this while keeping the bidirectional relationship between User and UserProfile?

A possible solution that I came across was to enforce lazy loading on one of the two references, but I wanted to know if there’s any other options.

1 Comment
2024/10/31
23:51 UTC

1

Share Coroutine Context

Is it okay to share the same coroutine context across different coroutines? I tested it and it seems to be working fine.

val context = Dispatchers.IO + myThreadLocal.asContextElement() + myThreadContextElement
val deferredResultOne = async(context) { /* some work */ }
val deferredResultTwo = async(context) { /* some work */ }
val resultOne = deferredResultOne.await()
val resultTwo = deferredResultTwo.await()
3 Comments
2024/10/31
18:46 UTC

2

Generating Dokka Docs for Dependencies

Is it possible to automatically generate and include the docs of specific dependencies into my projects documentation. Some of my dependencies do not have an documentation that I can add via externalDocumentationLink.

1 Comment
2024/10/31
16:46 UTC

0

Kotlin: Properties vs Variables

My friends often ask me about what's the difference between Properties and Variables in Kotlin all the time I spend my time explaining this. Yet no such questions from my friends programming in other languages. And the reason why this confusion is happening is that you define properties, variables and properties with variables in Kotlin using the same syntax. I recorded a small video which clearly shows the difference between all these cases: https://youtu.be/OPe84g2o7f0

9 Comments
2024/10/31
15:34 UTC

1

Question: Constructors

I am currently learning Kotlin and I have had questions about how to implement value objects in this language in the most elegant way.

The first and simplest case is the abstract class IdValue that is responsible for managing the application's ids. The reason for encapsulating this class is because I always want it to be serialized or deserialized in the same way.

In Python I would do it like this:

import uuid
from abc import ABC, abstractmethod
import re


class IdValue(ABC): # Abstract class
    def __init__(self, value: uuid.UUID):
        self._value = value  # Private
    @classmethod
    def new(cls):
        """Create a new id."""
        return cls(uuid.uuid4())

    @classmethod
    def from_string(cls, value: str):
        return cls(uuid.UUID(value))

    def to_string(self):
        return self._value.hex

class RoomId(IdValue):
    """Room Id. Note from_string and new methods will create a RoomId instance.-"""

I don't see the way to translate the classmethods in Kotlin since the closest thing is the companions but I can't reuse them in the child classes. And I must create the constructors in the child class.

Another slightly more complex case, but you can see the usefulness of this class. In some strings I want the data to be validated if they are obtained from an external source. In the child classes they would only have to implement the corresponding regexp.

class RegexpValue(ABC):
    def __init__(self, value: str):
        self._value = value

    @classmethod  #Note in python is not possible have abstract properties. So in some moments could be tricky.
    @abstractmethod
    def _regexp(cls) -> re.Pattern:  # protected method
        pass

    @classmethod
    def from_string(cls, value: str):
        cls._validate(value)
        return cls(value)
    
    @classmethod
    def _validate(cls, value: str):
        if not cls._regexp().match(value):
            raise NotImplementedError

class Name(RegexpValue):
    _REGEXP = re.compile("[a-Z]")

    @classmethod
    def _regexp(cls) -> re.Pattern:
        return cls._REGEXP

I think that create a constructor with a flag to validate data is too ugly.

9 Comments
2024/10/31
10:48 UTC

0

Suggestion I need

Suggest some resources to learn kotlin advance in order to be a android developer

2 Comments
2024/10/31
09:44 UTC

0

Can Kotlin Dethrone Python as the AI Language of Choice?

Python's dominance in AI is undeniable, but is its reign coming to an end? Kotlin, a modern language, boasts robust features rivaling Python's, especially in object-oriented programming. While Python's AI ecosystem remains unmatched, Kotlin's versatility, null safety and concise syntax might just bridge the gap.Will Kotlin's advantages propel it to the top, or will Python's vast library support and community keep it reigning supreme? Share your thoughts on the future of AI programming languages.

27 Comments
2024/10/31
07:19 UTC

1

Question about a parameter in a function

I can't understand what's happening in the function in the part that's marked in blue.
It's confusing, because both elements have the same name.

Can anyone explain why that parameter is used?

I got this code from a video I watched on Youtube.

https://preview.redd.it/wtiu94l1pyxd1.png?width=885&format=png&auto=webp&s=d21affb95629c4655e255c73749dbf62ef8ebac3

7 Comments
2024/10/30
21:31 UTC

14

What are some of the best resources to get started with Kotlin Multiplatform?

I am a native android developer who already has experience working with Kotlin projects. Do you recommend a particular Udemy course, a YouTube playlist, a blog or a codelab? Where do I get started? What are the best practices? Ping anything that helped you.

8 Comments
2024/10/30
17:30 UTC

13

TypeAlias Show - Immutable and Persistent Lists in Kotlin

1 Comment
2024/10/30
15:00 UTC

2

Need help regarding resources( beginner )

Hi, I am a React Native developer with over 2 years of experience. I am learning Kotlin to gain a deeper understanding of Android systems and to create apps that require more control over system resources, which can be challenging in React Native. I have been learning Kotlin for more than 4 months. I need help finding resources that demonstrate how to use all permissions ( location, all apps list, intercept all network request) examples. If you know of any places where I can find this information, please let me know. It would mean a lot to me!

4 Comments
2024/10/30
13:26 UTC

4

Step into transient dependency

Disclaimer - I am an experienced .net developer (for more than 20 years), but totally new in kotlin/intellij environment.

During debugging, how can you step into and debug a transient dependency? Consider this project: https://github.com/eu-digital-identity-wallet#android-overview

When running eudi-app-android-wallet-ui project in Android Studio, I can step into the eudi-lib-android-wallet-core project, but not further into the eudi-lib-jvm-openid4vci-kt for example. Also when I try to CTRL+click a class in eudi-lib-jvm-openid4vci-kt, I get 'Cannot find declaration to go to'.

I tried many different things but so far nothing worked...

- Settings -> Advanced Settings -> Build Tools.Gradle -> Download sources

- I downloaded the source code for eudi-lib-jvm-openid4vci-kt and it's jar file. Then I added the jar file as a project dependency (Project Structure -> Dependencies). Now I can CTRL+click the class, but I get a decompiled class without method implementations. Now I am able to click 'Choose sources' where I select the folder with the projects source code, but nothing happens

- I downloaded all the dependencies as jar/aar files and put them into a lib folder, and then set the dependency to this folder instead of the one from the maven repository. Currently I am testing this option, but have different problems because some dependencies are not recognized...

Any help would be much appreciated, thanks :)

0 Comments
2024/10/30
13:15 UTC

1

Kotlin custom serialization - Linear json structure for nested data classes

I have a couple of data classes like below

data class Base (
  val prop1: String,
  val prop2: String
)

data class Derived (
  val base: Base,
  val prop3: String
)

The serialized form of Derived type looks like this

{
  "prop1": "value1",
  "prop2": "value2",
  "prop3": "value3"
}

I can write custom serializers using kotlinx for the derived class, but I'll be having many classes like Derived class which will have a field of Base type. I don't want to write custom serializer and de-serializer for every one of the type.

What options do I have? I'm just looking for more convenient ways to add new types, without writing custom serializers for each of them.

5 Comments
2024/10/30
11:14 UTC

0

When developing a Compose application

You can use the `koinInject` function to inject any instance or `koinViewModel` to inject a `ViewModel`.

Instances injected via `koinInject` will follow the lifecycle of the Composable they are used in, releasing the instance when the Composable is disposed. `ViewModel` instances will adhere to the standard `ViewModel` lifecycle.

https://preview.redd.it/lcd1g0jjgpxd1.png?width=544&format=png&auto=webp&s=83d120af7206736fa4577afab291f7f393724d01

0 Comments
2024/10/29
14:27 UTC

0

Is it good idea to do DSA & leetcode in kotlin? If yes, what are some good resources?

I have been in software industry for 4 years, I have mostly worked on enterprise softwares and hence most of the time coded in Java. My current company uses Kotlin and I have been using it in since last 6 months. It feels so good to write code in Kotlin.
I am looking of switch again and most of companies I would like to join use leetcode style interviews. I have already tried leetcoding in Kotlin and its way way better than Java. I love it. The only problem is solutions written in FP style don't perform the best. Even though time complexity remains same, using for loop and multable variables makes it perform better.
I am currently just playing with arrays and strings, but for advance topics I don't know should I use kotlin or not. Many youtube videos are in python or c++. Wanted to know if anyone has tried and cracked leetcode with Kotlin language and if its the right choice.

19 Comments
2024/10/28
20:04 UTC

Back To Top