Help with polymorphic deserialization

Trying to write a websocket app where the type of data is determined by event,

I found help with polymorphic serialization but couldnot find deserialization

interface WSEvent { val event: String } interface WSData<T> { val data: T } @Serializable data class WSMessage<T>(override val event: String, override val data: T) : WSEvent, WSData<T> fun getWSEvent(data: String): String { return Json.decodeFromString<WSEvent>(data).event } fun <T> getWSData(data: String): T { wsJson.decodeFromString<WSData<T>>(PolymorphicSerializer(WSData::class), data).data return Json.decodeFromString<WSData<T>>(data).data } 

i get the following error:

kotlinx.serialization.json.internal.JsonDecodingException: Polymorphic serializer was not found for missing class discriminator (‘null’)

JSON input: {“event”:”validate”,”data”:””}

submitted by /u/ayushshrestha8920
[link] [comments]

Continue ReadingHelp with polymorphic deserialization

Navigating Kotlin’s Flexibility: Best Practices for Structured Code?

I’m working with a team that uses Kotlin in a very relaxed and unstructured manner. We seldom use classes, and instead, treat files as if they were packages containing various classes, similar to Java, but this approach isn’t consistent. Sometimes a file does a lot, while other times, it behaves as expected.

One of the key advantages of Kotlin is the ability to define functions at the top level of a file, making them accessible globally. However, this often leaves me feeling disoriented as I navigate through numerous files and standalone functions. It’s common to encounter functions that appear local but are actually located in distant files, which complicates understanding their context or relevance. Additionally, navigating the code can be challenging because we don’t always need to import functions when they are within the same global scope. This often leads me to question the origin of a function, resulting in frequent checks to determine its location and the file it belongs to.

This raises a question: is it possible to overuse such “free-form” coding?

In my practice, I’ve approached Kotlin coding similarly to Java, leveraging Kotlin’s additional features. I avoid nesting functions within functions within functions, which I find complicates understanding. I prefer to organize functions into packages and classes to clarify code organization and relationships. I generally steer clear of “global” functions tied to specific features or use cases, except for very generic utility functions, which are a significant benefit of Kotlin.

I mean, with Ktor we have for example something simple for creating an API that returns a Hello world string:

“`kotlin
fun main() {
embeddedServer(Netty, port = 8000) {
routing {
get (“/”) {
call.respondText(“Hello, world!”)
}
}
}.start(wait = true)
}
“`

(Pastebin https://pastebin.com/Rp8Y2WKR for readable formatting)

This is fine in itself, once you are familiar with Ktor and know what to expect.
However, once we start installing plugins, configuration, and the like, we suddenly end up with 5-10 nested {} code. This this the new norm? How would you even organize code like this?

I’m interested in learning about your experiences with Kotlin and what you consider to be “best practices” – especially combined with a Ktor project if possible.

Big thanks in advance

submitted by /u/ZynthCode
[link] [comments]

Continue ReadingNavigating Kotlin’s Flexibility: Best Practices for Structured Code?

Gradle sourceSet Dependancy Mess – Am I going crazy?

Hey all,

So I’ve been trying to stand up a KTor Server app, and I’ve been using sourceSets to organize code. However one of the issues that I’ve been having is that dependencies seem to have to be defined twice for some reason in the buildscript, one in the primary dependencies block and the other in the sourceSet configuration block, ie:

“` sourceSets { create(“pluginGMaps”) { java.srcDir(“src/pluginGMaps/kotlin”) resources.srcDir(“src/pluginGMaps/resources”) dependencies { // One here implementation(“io.ktor:ktor-client-core:$ktor_version”) // … } } create(“sharedDataClasses”) { java.srcDir(“/src/sharedDataClasses/kotlin”) resources.srcDir(“src/sharedDataClasses/resources”) } }

tasks.test { useJUnitPlatform() }

dependencies { implementation(“io.ktor:ktor-server-core-jvm”) // Another one here “sharedDataClassesImplementation”(“io.ktoe:ktor-client-core:$ktor_version”) // … } “`

If I leave out the first declaration (“One here”), the project compiles, but when something in the sourceSet calls back into the library, the build throws a NoClassDefFound exception, while if the latter (“Another one here”) doesn’t exist, it won’t build at all.

I don’t have a lot of experience with Gradle in general, does anyone know of a better or the correct way to do this? Thanks!

submitted by /u/EnterpriseGuy52840
[link] [comments]

Continue ReadingGradle sourceSet Dependancy Mess – Am I going crazy?

Nested LazyColumn in Jetpack Compose

Jetpack Compose Series Episode IV— Nested Lazy Column

When displaying groups of elements, we generally use columns and rows. But when it comes to displaying long lists, compose provides efficient alternatives like LazyColumn and LazyRow, which only render visible items in the screen.

This lazy loading approach improves performance and reduces memory consumption.

Before implementing Nested LazyColumn, let’s briefly go through some basics about available components to render large list.

I. LazyColumn & LazyRow

When rendering large datasets, we often use LazyColumn for vertical arrangements and LazyRow for horizontal.

Similar to RecyclerView, it support reverse layout, orientation adjustment, multiple view types, etc.

LazyColumn {
items(data) { item ->
Box(
modifier = Modifier
.height(100.dp)
.fillMaxWidth()
.background(Color.Magenta)
.padding(16.dp)
)
Spacer(modifier = Modifier.padding(8.dp))
}
}


LazyRow {
items(data) { item ->
Box(
modifier = Modifier
.width(100.dp)
.height(200.dp)
.background(Color.Magenta)
.padding(16.dp)
)
Spacer(modifier = Modifier.padding(8.dp))
}
}

Index Position in LazyList

LazyColumn and LazyRow provide an itemsIndexed function that allows us to access the index number of each item in the list.

  LazyColumn {
itemsIndexed(items = dataList) { index, data ->

if (index == 0) {

}else{

}
}
}

Unique ID for LazyList

The key parameter in the LazyList ensures that each item in the list has a stable and unique key, which is essential for efficient list updates and performance optimization.

LazyColumn {
items(items = allProductEntities, key = { item -> item.id }) { product ->
ProductItem(product) {
onProductClick(product.id.toString())
}
}
}

Multiple ViewType

If we want to display different view types, such as headers, footers, or items with distinct UI representations, we can use the index or check view-type from the list to display it accordingly.

Header & Footer Items in LazyColumn
LazyColumn {
itemsIndexed(items = dataList) { index, data ->

if (index == 0) {
HeroCard(data)
} else {
when (data.categoryType) {

CategoryType.Recent -> {
RecentItem(data) {
onRecentItemClick(data.id))
}
}

CategoryType.Popular -> {
PopularItem(data) {
onPopularItemClick(data.id))
}
}

else -> {
TrendingItem(data) {
onTrendingItemClick(data.id)
}
}

}
}
}
}

Moreover, If there’s a need to append additional items to the list or add different components, we can use item function inside LazyList.

 LazyColumn {
item {
HeroCardItem()
}
items(data) { item ->
Box(
modifier = Modifier
.fillMaxWidth()
.height(200.dp)
.background(Color.Magenta)
.padding(16.dp)
)
Spacer(modifier = Modifier.padding(8.dp))
}
item {
FooterCardItem()
}

}

@Composable
fun HeroCardItem() {
Column {
Box(
modifier = Modifier
.height(500.dp)
.fillMaxWidth()
.padding(16.dp)
){
...
}
Spacer(modifier = Modifier.padding(8.dp))
}
}

@Composable
fun FooterCardItem() {
Column {
Box(
modifier = Modifier
.height(100.dp)
.fillMaxWidth()
.padding(16.dp)
){
...
}
Spacer(modifier = Modifier.padding(8.dp))
}
}

II. LazyGrid

With Compose, we can easily create grids using the Grid composable and its variants, such as LazyVerticalGrid and LazyHorizontalGrid with lazy loading capabilities.

We can define rows and columns in a grid by using the following types:

columns for LazyVerticalGrid and rows for LazyHorizontalGrid

— Adaptive: Adjusts the size of rows or columns based on content and available space.

--> (columns = GridCells.Adaptive(minSize = 128.dp))
--> (rows = GridCells.Adaptive(minSize = 128.dp))

— FixedSize: Specifies a fixed size for rows or columns.

--> (columns = GridCells.FixedSize(100.dp))
--> (rows = GridCells.FixedSize(100.dp))

— Fixed: Sets a fixed number of rows or columns.

--> (columns = GridCells.Fixed(4))
--> (rows = GridCells.Fixed(4))
--> (columns = StaggeredGridCells.Fixed(2)),
@Composable
fun ExampleVGrid(data: List<String>) {

LazyVerticalGrid(
columns = GridCells.Adaptive(minSize = 128.dp),
contentPadding = PaddingValues(8.dp)
) {
items(data.size) { index ->
Card(
modifier = Modifier
.padding(4.dp)
.fillMaxWidth(),
) {
Text(
text = data[index],
fontWeight = FontWeight.Bold,
textAlign = TextAlign.Center,
modifier = Modifier.padding(16.dp)
)
}
}

}

}

III. Flow Layout

Flow layout helps us arrange our elements in a natural flow. We have FlowColumn and FlowRow to arrange vertically and horizontally.

Note: FlowRow and FlowColumn are experimental.

Read more about FlowLayout

Kt. Academy

Nested LazyColumn in Jetpack Compose was originally published in Kt. Academy on Medium, where people are continuing the conversation by highlighting and responding to this story.

Continue ReadingNested LazyColumn in Jetpack Compose

How do I get compose working on my raspberry pi?

I have recently gotten myself a raspberry pi 5 (4GB) to run a jetbrains compose app I developed.

When running it I get one of these errors depending on how I run the program:

  • Some sort of SIGSEGV runtime error with the skiko library
  • Cannot create Linux GL Context

I have tried gradle run and running a compiled uber jar and the .deb package and cannot get it to work.

I have installed gradle, kotlin and java via SDKMAN!

Thanks in advance

submitted by /u/Lolmerkat
[link] [comments]

Continue ReadingHow do I get compose working on my raspberry pi?

Need Advice about mobile dev

Hello everyone! I’m new to mobile development and planning to start with native Android development using Kotlin. I’m considering whether to learn Kotlin alongside Jetpack Compose or to begin with the traditional XML and Java/Kotlin approach. Could you share the pros and cons of each, especially for a beginner? Additionally, having some background in JavaScript, I’m also curious about cross-platform technologies like Flutter and React Native. Which would you recommend considering job market trends and the learning curve for someone open to mastering new technologies? My goal is to get hired by the end of this year after self-learning and building projects. I would appreciate any advice on the best learning resources, types of projects that would impress potential employers, and insights into the supportiveness of the communities for Kotlin, Flutter, and React Native. Thank you!

submitted by /u/namingkay
[link] [comments]

Continue ReadingNeed Advice about mobile dev

Compiler-plugin that does Scala-like interpolation a.k.a. JEP-430 for Kotlin

(UPDATE I am currently waiting for approval from plugins.gradle.org to be able to publish the plugin)

I just created a Kotlin compiler-plugin that does Scala like string interpolation for Kotlin, in the Java world this is known as String Templates i.e. JEP-430. This plugin allows Kotlin to capture “the $dollar $sign $variables” in Strings before the variables are spliced into the surrounding string. This allows for third-party Kotlin libraries to create functionality like sql-prefixed strings e.g:

val ps: PreparedStatement = sql("SELECT * FROM person WHERE id = $id" AND name = $name) 

So you can capture the “id” and “name” variables and put them into a PreparedStatement correctly without worrying about SQL-injection attacks!

This can be implemented as simply as:

class SqlInterpolator(val connection: Connection): Interpolator<Any, PreparedStatement> { // Parts is ["SELECT * FROM users WHERE id = ", " AND name = ", ""] // Params is [`id`, `name`] i.e. [1234, "Joe"] override fun interpolate(parts: () -> List<String>, params: () -> List<Any>): PreparedStatement { val stmt = connection.prepareStatement(parts().joinToString("?")) for ((arg, i) <- params().zipWithIndex) { stmt.setObject(i + 1, arg) } return stmt } } 

There’s a lot more that you can do when you can capture the values of “$dollar $sign $variables” in a string. For example, Scala libraries like Doobie and Quill use these string-templates to implement a rich set of functionality by returning custom objects from
sql(“…”) strings that can then be spliced into other sql(“…”) objects.

Enjoy!

https://github.com/deusaquilus/terpal

submitted by /u/deusaquilus
[link] [comments]

Continue ReadingCompiler-plugin that does Scala-like interpolation a.k.a. JEP-430 for Kotlin

Can someone explain what’s going on here to a Kotlin noob?

Hello, your local Kotlin noob here trying to understand ktor basics. I understand the following code as a series of trailing lambdas used to configure a customer route with four http methods. I understand that the route, get, post and delete functions are imported from the routing module and also methods of the Route class. There are then a bunch of things I don’t understand.

I think customerRouting is a new function being declared on the Route class, but I don’t get how that works.

I don’t know which scope of route, get, etc. are being called.

I don’t understand how calling a series of http method function within the route trailing lambda results in those http method/paths being bound to the route itself.

I would appreciate any and all explanations or advice, even if it’s just pointing me towards resources that explain Kotlin or ktor concepts that I need to learn in order to fully understand this code.

package com.example.routes import io.ktor.server.routing.* fun Route.customerRouting() { route("/customer") { get { } get("{id?}") { } post { } delete("{id?}") { } } } 

submitted by /u/rover_G
[link] [comments]

Continue ReadingCan someone explain what’s going on here to a Kotlin noob?

End of content

No more pages to load