/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

80,924 Subscribers

1

I need help, plz

Hii, im trying to connect a Firebase to my Android , but when im trying to update the database with the data I pass through my app, it doesnt do anything. Help please

0 Comments
2024/05/14
02:23 UTC

8

Can you explain higher order/level functions to me like I'm 5?

Hi friends. In learning kotlin I'm finding most of the explanations lack luster surrounding higher order functions and passing them as arguments. Specifically I'm trying to understand why you would do this. Most of the examples just sort of show you how to do but less about why you would do it. TIA!

8 Comments
2024/05/13
22:08 UTC

3

Suggest backend framework

I want to write small project for me and friends, something like online flash drive, but as for "storage" it will use system of other clouds

I have wonderful experience of using python FastAPI, especially autodoc and pydantic models

I checked spring and it semt to quite large for such a small project, ktor looks interesting, but i heard it has a lot of cons tho

So what will u suggest?

9 Comments
2024/05/13
19:17 UTC

1

What is the naming convention for files with functions

Hello there I can’t seem to find the proper naming convention for files with both functions e.g. lowercase methods not extensions and @Compostable functions e.g. uppercase functions that return composables :)

Should I call the files uppercase always with the name of what they hold ?

Example :

public fun somefunction()

Should it be stored in file somefunction.kt

@Composable public fun SomeComponent()

Should it be stored in file SomeComponent.kt ?

12 Comments
2024/05/13
16:58 UTC

3

Need help with JNA on Kotlin Multiplatform

Hi guys.

Im trying to set messaging between two instances of my kotlin desktop (windows) project.
The app is a music player and the idea is that once an instance of the app is already running, new instances will message that instance with file to play instead of opening new instances, then close them.

I tried using a local file to read and write but its not reliable enough, so now im trying to use JNA to send and receive messages between the two instances.

this is my function to listen and receive messages:

private fun setupMessagesListener(){
    val user32 = User32.INSTANCE
    val messagePump = Thread {
        val msg = MSG()
        val window = user32.FindWindow(null, "MyAppName")

        User32.INSTANCE.PostMessage(window, WinUser.WM_USER, WinDef.WPARAM(0), WinDef.LPARAM(0))

        while (user32.GetMessage(msg, window, 0, 0) > 0){
            if (msg.message == WinUser.WM_COPYDATA){
                val copyData = COPYDATASTRUCT(msg.pointer)
                val chars = copyData.lpData.getCharArray(0, copyData.cbData / 2)
                val filePath = String(chars)
                val file = File(filePath)
                if (file.exists()){
                    handleFileArgument(filePath)
                }
            }
        }
        user32.TranslateMessage(msg)
        user32.DispatchMessage(msg)

    }
    messagePump.start()}

and this is the function to send messages:

private fun sendFilePathMessage(filePath: String){

    val user32 = User32.INSTANCE
    val activeInstance = user32.FindWindow(null, "MyAppName")

    activeInstance?.let {
        val wideString = filePath.toCharArray()
        val size = (wideString.size * Char.SIZE_BYTES) + Char.SIZE_BYTES
        val buffer = Memory(size.toLong())
        buffer.setWideString(0, filePath)

        val copyData = COPYDATASTRUCT().apply {
            dwData = ULONG_PTR(0)
            cbData = size
            lpData = buffer
        }
        val pointer = copyData.pointer
        copyData.write()

        user32.SendMessage(activeInstance, WinUser.WM_COPYDATA, null, WinDef.LPARAM(Pointer.nativeValue(pointer)))
    }
}

when i debug my listener function, it always stop at while condition and never gets inside the loop, nor it comes back.
when i try to evaluate
user32.GetMessage(msg, window, 0, 0)
the debugger never finishes its just stuck.

1 Comment
2024/05/13
16:08 UTC

1

How to Share ViewModels in Compose Multiplatform (with Dependency Injection!) - using Koin

Sharing a brilliant new video by The Philipp Lackner :

How to Share ViewModels in Compose Multiplatform (with Dependency Injection!) using Koin for DI - as Koin is fully KMP - KMP-compatible

https://www.youtube.com/watch?v=O85qOS7U3XQ

5 Comments
2024/05/13
08:20 UTC

2

Ktor: SSLHandshake exception when trying to connect websocket with wss only in browsers

I have written a server code with KTOR & hosted it in AWS EC2 instance, it is working fine with android and desktop but our client wanted a web app so we developed it in KMP, compose multiplatform, everything was going great but as our webapps runs using HTTPS we have to use WSS so we followed the official docs to configure SSL using this link and while testing it in postman WSS sockets are also getting connected so we deployed it in our test server and tried it in chrome which resulted in this SSLHandshakeException

https://preview.redd.it/dlga2jtp140d1.png?width=2256&format=png&auto=webp&s=a4bab006ff1cf875170ec5bbafc859f900695d47

here is how we create a Keystore and application.conf is as follows

application.conf

ktor {
    deployment {
        port = 3456
        port = ${?PORT}
        sslPort = 3457
        sslPort = ${?SSL_PORT}
    }
    security {
        ssl {
            keyStore = keystore.jks
            keyAlias = sampleAlias
            keyStorePassword = 123456
            privateKeyPassword = 123456
        }
    }
    application {
        modules = [ my.Package.module ]
    }
}

to generate Keystore:

val keyStoreFile = File("build/libs/./keystore.jks")
val keyStore = buildKeyStore {
    certificate("sampleAlias") {
        password = "123456"
        domains = listOf("127.0.0.1", "0.0.0.0", "localhost")
    }
}
keyStore.saveToFile(keyStoreFile, "123456")

as I have already mentioned web sockets are working in postman but they are failing when testing in browsers, even in android & desktop we started using WSS instead of Websockets they are working fine so any solutions or any hints would be very very helpful

I have been trying to get a solution for this in stackoverflow too if I get any answer I will update it here

4 Comments
2024/05/13
03:24 UTC

21

Which backend framework supporting Kotlin has the best job placement rate?

Im a mobile dev , and moving to backend world now. As a result, Which backend framework supporting Kotlin has the best job placement rate?

Additionally, which good courses for that backend framework? Because I see many courses out there which have outstanding reviews, but I can not pay all of courses :(.

Many thanks.

26 Comments
2024/05/12
12:29 UTC

0

Can't figure out why Intent is being shown as an error

https://preview.redd.it/0lduvvozfzzc1.png?width=1125&format=png&auto=webp&s=9adb00685de87d54140377d2e582f759608d3e79

<html>None of the following functions can be called with the arguments supplied:<br/>public constructor Intent(packageContext: Context!, cls: Class\&lt;\*\&gt;!) defined in android.content.Intent<br/>public constructor Intent(action: String!, uri: Uri!) defined in android.content.Intent

this is the error message im getting

2 Comments
2024/05/12
11:41 UTC

6

How do I run a Kotlin gradle project created in IntelliJ using the command line?

Considering the fact that I've found nothing on this from Googling I'm sure this is somehow a bad question but I've spent around 15 minutes looking everywhere lol

I've got a Kotlin project that uses gradle and have been working on it in IntelliJ but I'm looking toward moving it off IntelliJ onto my VPS and want to know how to run the project via command line before I do so.

Every time I try to just use the kotlin command to run the main function it says it couldn't find the Main class. Are there special arguments I need to add or should I be somehow running it using the gradle daemon (and how would I do so)?

9 Comments
2024/05/12
02:30 UTC

6

How can I store and retrieve an AnnotatedString with formatting from Firebase Firestore?

I'm currently storing and retrieving an `AnnotatedString` with formatting from Firebase. However, my current approach saves the string, but upon retrieval, I receive a JSON string. I'm unsure how to convert this string back into a formatted `AnnotatedString`. Can someone assist me with this? Alternatively, is there a simpler method to achieve this?

override suspend fun createNote(createNote: CreateNote): Flow<Result<Boolean>> {
    return flow {
        try {
            val documentReference = firestore.collection("notes").document()
            val jsonText = Gson().toJson(createNote.text)
            val noteMap = hashMapOf(
                "text" to jsonText,
                "title" to createNote.title,
                "link" to createNote.link,
                "image" to createNote.image,
                "userID" to firebaseAuth.currentUser?.uid,
                "date" to createNote.date,
            )

            documentReference.set(noteMap).await()
            emit(Result.Success(true))

        } catch (e: Exception) {
            val errorMessage = when (e) {
                is FirebaseFirestoreException -> e.localizedMessage
                    ?: "Unknown Firebase Auth Error"
                else -> e.localizedMessage ?: "Unknown Error"
            }
            emit(Result.Error(errorMessage))
        }

    }
}
6 Comments
2024/05/11
16:16 UTC

8

[compose multiplatform] Is there a good example of master-detail implementation?

Is there a good example of master-detail implementation using org.jetbrains.androidx.navigation?

3 Comments
2024/05/11
12:51 UTC

2

Declaring Variables and Values

Hi, I have an assignment I am on for my intro to programming class, I am working with Kotlin.

I will explain as best as I can.

I was writing the code for lines 25 & 28. When I ran my code it told me that val cannot be reassigned. I did at first declare my "total" var as a val, so I changed it from val to var. Reran my code. It still throws the same exact error, as if I didn't change the val to a var. I made a new .kt file, pasted my code into it, and it is still saying val cannot be reassigned. What am I doing wrong? How can it still be declaring itself as a val when I changed it to var? Especially creating a whole new .kt file. Looking forward to some answers. Thank you for your time.

https://preview.redd.it/qfvkymvdtpzc1.png?width=2559&format=png&auto=webp&s=e6d79d8b0cc081910536d5521bef2f9ebe59ecac

9 Comments
2024/05/11
03:17 UTC

7

Server side rendering with Kotlin react?

I’m working on an LLM chat application that makes it easy to share and learn about data. If you’re curious you check it out here. It works similar to chat gpt in that it gives users a chat interface. Where I’m hoping to differentiate is

  1. Data ingestion, making it easy to ingest large amounts of data from various sources into what I call “collections”

  2. The sharing side of things. Make it easy to put your chat on the public internet so other people can interact with your data. I know Chatgpt has a share feature but this would take a things a step further and enable others to pick up where you left off and further ask questions about your collection. In addition I want to make it so these chats are indexed by Google so that they appear when people search relevant keywords.

That brings me to my question. I’ve built this app using Kotlin react and am now trying to think of how I can render a chat server side. The goal would be to create a static version of the page with the relevant content already in place so it can be indexed by Google. I know with JavaScript this is what nextjs is for but I don’t know how to accomplish this with Kotlin.

Also the goal of server side rendering is seo. If there’s another way of accomplishing the same thing please lmk!

3 Comments
2024/05/10
23:52 UTC

0

The app auto stops after a while

I'm new I built an app that views my website with "webView", the website includes an audio stream but the problem is that the audio stops by it self after around 10-15min for some reason,, I found out that I need to add background and foreground services but it's not working

I did something I'm not sure about and that app worked in the background even when the app is not on the Active applications, like literally the audio became built-in with the system LOL ,, I need to go back to the app and press the play button twice to stop tye audio

Anyone can help me with it ?

4 Comments
2024/05/10
20:17 UTC

17

Kotlin backend

Hi guys

I'm new in Kotlin, Do you you have any recommendations for learn backend with kotlin, or should I start with nodeJs? I'm Flutter developer, but I would like to explore Backend development and while reading documentation I came across Kotlin as a backend option

25 Comments
2024/05/10
18:08 UTC

2

How do you split SQL table entities when performing code modularisation?

Hi everybody.

My team is not in the process of separating our existing codebase into separate modules. We're using Kotlin on the backend, Gradle as a build tool. Backend now is one big Gralde module so everything is accessible from everywhere.

We are now trying to understand how we should approach the following. We're using Exposed library for SQL related operations. In our codebase we have many places where tables from one domain are joined with tables from the other one. As an example,

select t2.*
from table1 t1
         left join
     table2 t2 on t1.t2_id = t2.id
where t1.date > now();

where t1 is a table from one domain D1, t2 is a table from the domain D2.

When we're going to extract D1 and D2 table entities into the different modules, we cannot use tables D1 in D2. It's a requirement to make table entities inaccessible from other modules to have a strict divide on what belongs to what. As now we have a problem that "everything calls everything" and we're trying to overcome it by modularisation. It's not only about table entities but that's another non related topic.

I can only come up with a following solution. For the query above, D1 module exposes an interface that allows to query all the records like the following

select t1.id
from table1 t1
where t1.date > now();

D1 returns ids of a t1. And then in module D2 we retrieve t2 records. We pass t1 ids as an input parameter. So something in a sense of

select t2.*
from table2 t2
where t2.id in :t1_ids;

This solution seems logical. As it makes sense to do it in this way. Of course, performance will slightly suffer as instead of one round trip to the DB it would be two but I'm not worrying too much about it.

But maybe I'm missing something and there is another way of overcoming this. Did anyone of you did something similar in the past? How did you approach it? We also considered just to have tables being accessible from everywhere, meaning they won't be extracted to a separate module with an `internal` access modifier. But decided to make requirements stricter to not fall to the same problem we have right now in the future again. Would be glad to hear your thoughts.

16 Comments
2024/05/10
13:51 UTC

5

Generalising all the things - Expert Kotlin Refactoring

In this mini-series we’ve been comparing Ktor (https://ktor.io/) with http4k (https://http4k.org), and now I’d like to be able to compare their throughput. I have some benchmarking code left over from the coroutines and Loom episode, so it would be nice to use that, but it is very much specialised to http4k.

I suppose that I could just copy it for Ktor and then make edits, but where would the fun in that be? So today we’re going to look at how to progressively refactor a method into a function, and then to generalise all the things so that it no longer depends on any http4k types, and we can use it in other situations.

Oh and have IntelliJ automatically update the existing callers to use the new code as we make changes.

In this episode

  • 00:00:42 Review the benchmark method
  • 00:01:37 Change the method to a function by taking or returning field values
  • 00:01:55 IntelliJ extract parameter bug
  • 00:03:11 IntelliJ Extract Function bug
  • 00:04:13 And also other non-class dependencies
  • 00:04:54 IntelliJ Inline Function bug
  • 00:05:24 We can reorder calculations inside the function to get better timing
  • 00:06:39 Now pull the server out of the function by extracting the bits that don't need it
  • 00:08:32 Do the same again for the client
  • 00:10:29 Break action dependencies with lambdas
  • 00:10:53 IntelliJ Extract Variable bug
  • 00:11:58 Now we can use generics to break the last dependency
  • 00:12:56 Change the names to be more generic
  • 00:13:50 Reorder for sense
  • 00:13:58 Make our final option a strategy lambda
  • 00:15:24 Finally we can do better for our synchronised collection

This video is in a playlist of Ktor episodes (https://www.youtube.com/playlist?list=PL1ssMPpyqochUiQEM9PZ_P-9CbV1Il81B) and http4k (https://www.youtube.com/playlist?list=PL1ssMPpyqocg5TKqmiGWlvi3O5L8XPe8Q)

If you like this, 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/05/10
13:49 UTC

7

How do I run a kotlin program outside the IDE?

I know I must be missing something very obvious here...

I have a program I've written inside the JetBrains Kotlin IDE (IDEA community edition, running on windows 11. Everything set up as it defaults). I can compile and run the code from inside the IDE no problems. But then how do I run it from outside the IDE - preferably from a DOS command line? There just doesn't seem to be an executable file anywhere that I can find.

7 Comments
2024/05/10
12:40 UTC

14

Want to learn Android Development with Kotlin but all courses seem to be outdated

I consider myself an intermediate level developer. I want to expand my knowledge by learning Android development with Kotlin to create mobile apps. But all courses I have seen have comments that the course is outdated. I know that Udemy is not exactly the best place to learn new skills but I don't know where else I could check.

This also makes me wonder if learning Android development and Kotlin is even worth it. Are these technologies getting replaced by newer ones? It seems nowadays everyone is jumping to Go, Rust and frameworks that are multiplatform like Tauri, Flutter and React Native.

Is there still a market for Android development with Kotlin? And if so, where can I go to learn the latest versions of these technologies? Any thoughts/suggestions are appreciated.

11 Comments
2024/05/10
12:22 UTC

3

Kotlin Multiplatform - direct Kotlin-to-Swift export

Are there any unofficial news about the direct Kotlin-to-Swift export? I haven't found anything except a 6 month old blog post which just mentions that they are working on it.

https://blog.jetbrains.com/kotlin/2023/11/kotlin-multiplatform-development-roadmap-for-2024/

3 Comments
2024/05/10
11:55 UTC

0

Want to learn kotlin for android development

1 Comment
2024/05/10
10:22 UTC

0

Want to learn kotlin for android development

0 Comments
2024/05/10
10:22 UTC

3

Help what should I do next?

I'm on my Android development journey, and I have completed Kotlin Fundamentals from Philipp Lackner (Noobie to Pro playlist).  I'm confused about what I do next. Some options that I have are:

Android Fundamentals by Philipp Lackner:https://youtube.com/playlist?list=PLQkwcJG4YTCTq1raTb5iMuxnEB06J1VHX

Jetpack course playlist by Phillipp Lackner:https://youtube.com/playlist?list=PLQkwcJG4YTCSpJ2NLhDTHhi6XBNfk9WiC

If I'm doing something wrong, you can tell me a more efficient and better way on what to learn and from where to learn (a preferred free course or playlist). Feel free to give me suggestions. I'm just a beginner and would appreciate it if a more experienced person could share his or her learning path for Android development.

PS: I have 1.5 months to reach a skill level where I can make small projects (apps) like to-do apps and basic clones.

4 Comments
2024/05/10
06:23 UTC

10

Thoughts on the Lombok compiler plugin

Hi, we want to start writing Kotlin in our Java Android project and getting problem couldn't compile when using Lombok-annotated Java classes inside the Kotlin code, then I saw this https://kotlinlang.org/docs/lombok.html but it's marked as experimental. I wonder do you guys who are using this plugin have encountered issues with it?

Thanks in advance.

10 Comments
2024/05/10
06:14 UTC

Back To Top