/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

88,295 Subscribers

12

Take the Kotlin Multiplatform Survey and make your opinion heard

Are you a Kotlin Multiplatform developer? We want to hear from you! The Kotlin Multiplatform survey is now live, and this is your chance to share your feedback on the tools, ecosystem, and your overall experience. Your input will help us identify areas for improvement and prioritize future updates to better meet your needs.

🕑 The survey should take approximately 10 minutes to complete.

🎁 Fill out the survey with meaningful answers to get the chance to win a prize of your choice:

🔗 Take the survey.

Thank you for helping us make Kotlin Multiplatform even better!

1 Comment
2024/12/04
07:35 UTC

1

Async and await all with map operator

I have a question regarding a scenario where I have a list of data that I'm processing using an async block. Inside the async block, I'm performing some operations. Should the function being called within the async block be a suspend function to ensure that if the parent scope/job is canceled, the parallel tasks running within the async block are also canceled? Or is it sufficient for the function inside the async block to be a regular function?

suspend fun processRecords() {
    withContext(appDispatchers.io) {
        (1..1000000)
            .map {
                async {
                    processHeavyComputation()
                }
            }.awaitAll()
    }
}

suspend fun processHeavyComputation() {
    delay(100)
    println("some work")
}

fun processHeavyComputation() {
    println("some work")
}

and then calling this processRecords from viewModel using viewModelScope like below?

private fun processRecords(currentTimeMillis: Long) {
    currentJob = 
viewModelScope
.
launch
(dispatcher.io) {
        someObj.processRecords()
    }
}

fun stopProcessingRecords() {
    currentJob.cancel()
}
4 Comments
2024/12/03
15:14 UTC

19

UUID in Kotlin Multiplatform

1 Comment
2024/12/03
13:28 UTC

12

[Release] ksoup v0.2.1 – Faster, Modular HTML Parsing for Kotlin Multiplatform 🚀

We’re excited to announce ksoup v0.2.1, the latest update to our Kotlin Multiplatform library for seamless HTML parsing.

What’s New:

• Updated dependencies: Kotlin 2.1.0, jsoup 1.18.2, Ktor2 2.3.13, and more.

watchOS Support: Expanding cross-platform compatibility.

New Features: Charset support and ControllableInputStream.

Improved Performance: Faster I/O with fleeksoft-io.

• Modular updates for better clarity and efficiency.

Check it out:

• GitHub: fleeksoft/ksoup

We’d love to hear your feedback! 🚀

0 Comments
2024/12/03
07:22 UTC

0

Help Needed: Building a BLE Remote App to Fetch Data from Hardware Storage

Hi everyone,

I'm working on a BLE (Bluetooth Low Energy) remote app using Kotlin and need some advice from the community. The goal of this app is to connect with a hardware device via BLE, access its storage, and fetch the data stored on the device to display it in the app.

Here’s what I’ve done so far:

  • Set up BLE connection functionality in my app.
  • Successfully paired and connected the app to the hardware device.

Questions:

  1. What is the best approach to read/write data from the hardware's storage using BLE?
  2. Are there any specific libraries, frameworks, or examples you would recommend for this use case?
  3. What are the common pitfalls or challenges I should watch out for when implementing BLE storage communication?

I would appreciate any advice, tutorials, or code snippets that could help me tackle this challenge. Thanks in advance for your support!

P.S.: If you’ve worked on a similar project, I’d love to hear about your experience and any tips you can share.

Looking forward to your suggestions!

Best regards,
Sartaj Qamar

However, I’m stuck on how to access and fetch data from the hardware's storage once the BLE connection is established.

4 Comments
2024/12/02
23:33 UTC

3

How can I call Kotlin functions from a python script in the android app?

I have integrated a python script within the android app using chaquopy. Now I want create a data flow between the two. I figured out how to send data from kotlin to python, but now I want to expose a kotlin function that python can call to send data back to kotlin. But I am not able to find the right implementation. Would appreciate some help on what’s the best way to do this.

3 Comments
2024/12/02
20:38 UTC

0

USSD app

I'm l.ooking for a developer that can build a app that can remotely execute USSD codes and remotely send commands during the USSD session.

EDIT: it basically involves using the telephonyManager to dial USSD codes (eg. *123") This starts a USSD session with the mobile network where you can navigate through a menu using numbered responses.

4 Comments
2024/12/02
20:18 UTC

1

How to generate UML class or relationship diagram for my android studio jetpack compose project?

0 Comments
2024/12/02
17:58 UTC

25

Is Kotlin Multiplatform the Right Choice for a Netflix-Like App?

Hey Kotlin folks!

I’m exploring the client-side tech stack for a streaming app like Netflix.
The app will target Android and iOS, so I’m considering Flutter, React Native, fully native with Kotlin & Swift, or Kotlin Multiplatform!
*Features include DRM-protected video playback

What do you think is the most recommended option?
Of course, fully native is ideal in theory, but I’d love to hear your thoughts on balancing the effort of separate platform development with other options.

Thanks in advance! 🙏

25 Comments
2024/12/02
17:07 UTC

1

AndroidStudio asking to opt-in for @Serializable

Hi,

In AndroidStudio I can't use \@Serializable without opting-in for \@kotlinx.serialization.InternalSerializationApi. Why is that? None of the tuto I found online mentionthis and I can't find help on this problem online either.

In project pluggins I have id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false.
In module pluggins id("org.jetbrains.kotlin.plugin.serialization"), and in dependencies implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3").

Thanks

Edit:
module

plugins {
    application
    id("com.android.application") version "8.7.2" apply false
    id("org.jetbrains.kotlin.android") version "1.9.24" apply false
    id("org.jetbrains.kotlin.jvm") version "2.0.21" apply false
    id("org.jetbrains.kotlin.plugin.serialization") version "2.0.21" apply false
}

project

plugins {
    id("com.android.application")
    id("org.jetbrains.kotlin.android")
    id("org.jetbrains.kotlin.plugin.serialization")
}

android {
    namespace = "com.example.queezer"
    compileSdk = 34

    defaultConfig {
        applicationId = "com.example.queezer"
        minSdk = 16
        targetSdk = 34
        versionCode = 1
        versionName = "1.0"

        testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        getByName("release") {
            isMinifyEnabled = false
            proguardFiles(
                getDefaultProguardFile("proguard-android-optimize.txt"),
                "proguard-rules.pro"
            )
        }
    }
    compileOptions {
        sourceCompatibility = JavaVersion.VERSION_1_8
        targetCompatibility = JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

dependencies {
    implementation("androidx.appcompat:appcompat:1.6.1")
    implementation("com.google.android.material:material:1.11.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
    implementation("androidx.activity:activity-ktx:1.8.2")
    implementation("androidx.constraintlayout:constraintlayout:2.1.4")
}
4 Comments
2024/12/01
21:13 UTC

3

when versus if/else

With the preview of guards in 2.1.0, the decision between using when vs if/else if/else has moved towards when. Considering readability, "declarativeness", safety, conciseness, when in my opinion seems to generally win over if/else when there are 3+ branches. The main scenarios I can think of where if/else is still preferable are:

  • When there are only 2 branches. Because when adds the braces at the top and bottom, this would add a lot of vertical space usage that might not be justified for 2 branches

Examples:

if (a) x
else if (b) y

if (a) {
   x
}
else {
    x
}
  • When there are 3 or 4 branches, but braces would not be used for the if/else blocks. Similar to the above, the extra vertical space from a when here might not be worth it.

Examples:

if (a) x
else if (b) y
else if (c) z
else y + z
  • The if/else if/else expression can be in a single line. Here we might not want to expand it to 5 lines with a when statement.

Example:

if (a) x else if (b) y else z

The above cases, however, are fairly specific. Would you agree that in all other cases, and more generally when is preferable? Or do you have a different way of thinking about this decision?

9 Comments
2024/12/01
14:25 UTC

12

Advices or any insights to beginners kicking off their Kotlin journey

"I'm embarking on my Kotlin journey!" As a beginner, I'm keen on grasping the core concepts quickly. What are the most essential building blocks I should focus on? What are the best ways to learn Kotlin effectively and efficiently? What are some common pitfalls to avoid as a beginner Kotlin developer? Also, what are some practical projects that could help solidify my understanding and showcase my skills? Any tips, tricks, or resources from experienced Kotlin developers would be greatly appreciated!

9 Comments
2024/12/01
06:45 UTC

0

Hey i have a graduation project this year I will build an app connected to obd 2 elm 327 bluetooth The app will send to the user notifications for preventive maintenance changing oil,filters,tires ... When he cross a number of kilometeres like oil when u cross 10000 km u must change the oil of the

Hey i have a graduation project this year I will build an app connected to obd 2 elm 327 bluetooth The app will send to the user notifications for preventive maintenance changing oil,filters,tires ... When he cross a number of kilometeres like oil when u cross 10000 km u must change the oil of the car I have only six months to learn and build the app do u advice me kotlin or flutter I don't care about multi cross platforms of the beauty of the app All what i care is the succes of the idea Please need help asap

2 Comments
2024/11/30
23:35 UTC

23

I created a game map browser using Compose for Web and Ktor 3

During my last vacation, shortly after the release of Ktor 3 with WASM support, I felt inspired to start a new side project leveraging this technology. I created a game map browser for the game Oxygen Not Included using Compose Multiplatform and Ktor, paired with a Ktor server backend.

You can explore it at stefan-oltmann.de/oni-seed-browser/

The code is open-source, licensed under AGPL, and hosted on GitHub.

I believe it won't be long before Compose for Web is ready for production use. This side project also served as an opportunity to evaluate the current state of the technology, and I must say, I'm thoroughly impressed.

https://preview.redd.it/vx2q7wyhe44e1.png?width=3206&format=png&auto=webp&s=a4b4b6b93e751e508b24767a720e850df4893535

https://preview.redd.it/qm2hdvvje44e1.png?width=3206&format=png&auto=webp&s=088ff592bd016b65109cecd4ee3884a5512d5a1f

https://preview.redd.it/o0h7belke44e1.png?width=3206&format=png&auto=webp&s=e63b81530d48d513a0250bd8dc09c7180a5c1118

4 Comments
2024/11/30
23:08 UTC

4

[Release] Fleeksoft-io 0.0.2 – Kotlin Multiplatform I/O Library Update 🎉

Hey everyone!

We’re thrilled to announce the release of fleeksoft-io 0.0.2, our Kotlin Multiplatform I/O library, now packed with exciting updates to make your development experience even better.

🚀 What’s New in 0.0.2?

1️⃣ okio Extension

2️⃣ New URI Module

3️⃣ Standard and Extended Charset Modules

4️⃣ Dependency Updates

kotlinx-io bumped to version 0.6.0.

Kotlin bumped to version 2.1.0

🌐 Get Started

GitHub: https://github.com/fleeksoft/fleeksoft-io

🤝 Feedback & Contributions

We’re building this library for the community, and your feedback is invaluable! If you have feature requests, ideas, or bugs to report, feel free to open an issue or contribute directly.

Let us know what you think and how you’re using fleeksoft-io in your projects!

0 Comments
2024/11/30
19:38 UTC

0

what's wrong in this code?

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/fragmentContainerView6"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@+id/bottomNavigationView2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@id/textView3"
    app:navGraph="@navigation/navigation" />

this is what i get!

this is what i want!

5 Comments
2024/11/30
18:46 UTC

12

Hot Reloading Compose Apps with ClassLoaders (Firework Experiment)

0 Comments
2024/11/30
18:38 UTC

43

Solving Advent of Code with Kotlin Notebook!

2 Comments
2024/11/30
17:35 UTC

2

Compile Kotlin to Macos executable without full Xcode?

Want to compile my Kotlin command-line utilities to native macos for faster startup. When I tried with Kotlin-Native 2.0.21, got error saying full Xcode not found. I have Xcode Command-line Tools installed. Don't have enough disk space for full Xcode.

Any way to compile Kotlin to macos executable without full Xcode? Willing to use an older Kotlin version, if it previously worked with only Xcode Command-line Tools.

5 Comments
2024/11/30
17:15 UTC

1

Android app real-time SMS detection

Hello, I'm trying to build a native android app that heavily depends on SMS retrieval and processing. I have defined the permissions, granted them at run time and defined my broadcast receiever in the manifest.

Everything works. But the app is being flagged as malware by all devices.

I don't want to use foreground services as it will use an intrusive persistent notification. I just want the app to work in a way that it generates a Json from some SMS messages.

I know this is achievable, since Truecaller does it. I don't want persistent notifications and the app should work even when it's not in use.

Is there something I'm doing wrong? Truecaller does this perfectly even without being set as the default SMS app and it will not show any notifications, except for when you get the SMS.

How can I achieve this?

4 Comments
2024/11/30
16:30 UTC

12

AocKt v0.2.1: Testing library for Advent of Code Kotlin

Disclaimer! I am the library author.

Hey friends! I've been tidying up my library for advent of code and I'd love to share with you the 0.2.1 update and get your feedback. This is something that I used myself but released as a library. It provides a DSL for generating test cases for your Advent of Code puzzles.

I also wanted to try out Writerside, so I revamped the documentation with a new website. There is also a project template, if you'd like to try AoC with Kotin this year.

Good luck to everyone!

Advent of Code Kotlin: AocKt

1 Comment
2024/11/30
14:34 UTC

11

Is it worth it to transfer to learn kotlin or android dev if you already a java developer?

15 Comments
2024/11/30
11:23 UTC

5

When to start using coroutines (and threads)?

Hey,

I've recently learned about concurrency and parallelism with both threads and coroutines.

I wanted to actually understand how they work and are built on a deeper level. I also asked about them here, and your answers were really helpful. Now that I think I had learned and tried both for quite a bit, I'd like to start using them in actual side projects.

But here's my new question: When should I start using coroutines (and threads) ?

I mean, for Threads it's even harder to decide.

I know that both Threads and Coroutines have some kind of overhead, Coroutines less since they are implemented in the application-layer and have less overhead in general.

But since both have an overhead, it must mean that they only become viable to use at one point and can be bad if used too early.

Can you give practical advice on when using Threads and when using Coroutines becomes viable?

Threads for reading 2 files for some operation? Coroutines already when I have a db-call and a network-call in one function?

12 Comments
2024/11/29
19:11 UTC

10

Testcontainers, Postgres, Kotlin

If you check our Kotlin Gilded Rose codebase out of GitHub (https://github.com/dmcg/gilded-rose-tdd) and try to build it, you will find that you need to be running Postgres just in order to compile things, and then again in order to run the unit tests.

That’s not too much of an issue on my Mac, but with the expansion of the team we would like to set up a cloud continuous integration server, and there we are going to want to manage the Postgres lifecycle inside our build.

It would be a start if only there was a way to manage Docker containers in our tests. Containers in our tests ... Testcontainers!

In this episode

  • 00:00:35 Review our database lifecycle
  • 00:03:01 Never upgrade a thing just before recording
  • 00:05:12 DBItemsTests currently uses a running Postgres
  • 00:06:25 DBItemsTests has to clear the decks before running its tests
  • 00:07:16 Testcontainers allow a fresh database per test
  • 00:08:00 AI Assistant now lets us just type and tab
  • 00:08:57 Let's start a container for each test
  • 00:11:27 If we have a clean database, we're going to have to create the schema
  • 00:12:37 Run our migrations in the test with Flyway
  • 00:14:08 AI for error messages
  • 00:15:20 Debugging Flyway
  • 00:18:16 It turns out we need to add a dependency
  • 00:19:20 Now we have to match the database user to the migration user
  • 00:20:22 One last irritating intermittent issue
  • 00:23:26 Pragmatism FTW
  • 00:25:24 Now, is Testcontainers fast enough?

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

If you are going to be at KotlinConf 2025, or even just in Copenhagen in May, then you should totally be signing up for the workshop that Nat Pryce and I are running. It’s called Refactoring to Functional Kotlin, and will give you hands-on experience of taking legacy code and safely migrating it to a functional style. Places are limited, so buy now at https://kotlinconf.com/workhops

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/29
13:53 UTC

1

Is there a way to run a node.js module with ktor?

I've been wondering if it's possible to run specific modules with node.js while the rest of the backend runs on ktor.

For example, Bluesky has an SDK for Typescript but not for Kotlin, so the way to use it would be to create a microservice just for the Bluesky api.

Has anyone faced this kind of situation?

4 Comments
2024/11/29
12:44 UTC

5

Migrating Multi-Module Android Project to KMP While Preserving Modularity?

Our Android project follows a multi-module architecture with:

- 20 features

- Each feature is split into 4 modules:

  1. `data-private`: Repository implementations and use cases
  2. `data-public`: Interfaces, data classes, and entities
  3. `ui-private`: ViewModels, activities, and non-shared UI components
  4. `ui-public`: Reusable UI components

- Only the app module can access private modules (for DI purposes) to bind the implementation with the interfaces

- Using Koin for dependency injection

- Most core feature data layers have been converted to KMP modules

our target is to keep the native ui and share the business logic only

## Current Migration Progress

We've started migrating to KMP with the following approach:

  1. Successfully converted core features' data layers to KMP
  2. Attempted library approach by extracting data modules into a shared library

## Challenge

We're facing a architectural challenge with our library approach:

- Moving business logic and data modules into a single shared library compromises modularity

- Features that previously only depended on their own public data will now have access to both private and public data of all features

- This breaks our careful module isolation and risks creating unwanted dependencies

## Question

How can we migrate to KMP while maintaining our current modular architecture? Specifically:

  1. How to preserve module boundaries when sharing code with iOS?
  2. What's the recommended approach for maintaining feature isolation in KMP?
  3. Are there established patterns for migrating multi-module Android projects to KMP?

## Technical Details

- DI Framework: Koin

- Target Platforms: Android, iOS, data only with native ui

- Current Approach: Library-based sharing

5 Comments
2024/11/29
11:32 UTC

Back To Top