Klitos Kyriacou
01/09/2023, 11:36 AMval statement = connection.prepareStatement(
"""
UPDATE tablename
SET column1 = ?
WHERE column2 = ?
""".trimIndent()
)
2:
val statement = connection.prepareStatement("""
UPDATE tablename
SET column1 = ?
WHERE column2 = ?
""".trimIndent()
)
and various others.Nick Halase
03/02/2023, 9:28 PMerror(message: String)
messages?
1. System.getenv("GITHUB_SHA") ?: error("GITHUB_SHA is missing")
2. System.getenv("GITHUB_SHA") ?: error("GITHUB_SHA must exist")
groostav
03/15/2023, 9:48 PMclass ConvertedOldModelObject private constructor(oldCtorArg: OldJavaDomainType, ...) {
//...
companion object {
@JvmStatic @JvmName("create") operator fun invoke(oldCtorArg: OldJavaDomainType, ...) {
//some caching logic to try to avoid hanging on to allocaitons, a kind of poor mans constant pool
return CovertedOldModelObject(oldCtorArg, cachedArgs, ...)
}
}
}
pros:
• I get OldJavaDomainType oldThing = OldJavaDomainType.create(args...)
from java
• I get val x = OldJavaDomainType(args...)
from kotlin
cons:
• companion object operator fun invoke
seems like a kind of nifty hack, not sure how somebody else would feel stumbling across it
• reasonable alternatives like simply offering a global function for kotlin and a simpler fun create()
method for java seems sufficient, though slightly bloatierMustafa Ozhan
03/21/2023, 3:07 PMresourceProvider.kt
or viewExt.kt
.
Is it an official convention? I couldn’t find anything in Coding Conventions about itedrd
03/22/2023, 5:25 PMMark
04/09/2023, 4:01 AMfor (index in 0 until itemCount) {
2️⃣ repeat(itemCount) { index ->
KotlinLeaner
04/27/2023, 1:09 PMnull
or empty
. I tried to filter basic to avoid null code and replace with empty
1️⃣
fun filterMovieItemList(unfilteredList: List<MovieItem>): List<MovieItemModel> {
val movieItemModelList = mutableListOf<MovieItemModel>()
if (unfilteredList.isNotEmpty()) {
unfilteredList.forEachIndexed { _, movieItem ->
val movieDetails = movieItem.movieDetails
if (movieDetails != null && !movieDetails.name.isNullOrEmpty()) {
val icon = movieDetails.iconUrl ?: "xyz"
movieItemModelList.add(
MovieItemModel(
movieDetails.name,
icon,
movieDetails.summary ?: "",
)
)
}
}
}
return movieItemModelList
}
Tara Czutno
05/03/2023, 9:10 PMprivate fun buildClient(ten: String?) = BaseApiUrlBuilder(baseUrl, ten).build()
.let(defaultWebClientBuilder::baseUrl)
.build()
and BaseApiUrlBuilder looked like this
class BaseApiUrlBuilder(
private val url: String,
private val ten: String? = null,
) {
then BaseApiUrlBuilder was changed to:
class BaseApiUrlBuilder(
private val url: String,
private val ten: String? = null,
private val localPort: Long = 8080
) {
And we did not get a compiler error but later got a runtime error on the first block of code.
How can runtime errors like this be prevented? By using named arguments and having Detekt enforce named arguments? Other insights? Thanks.KotlinLeaner
05/05/2023, 8:44 AMenum class Stage(val title: String) {
ONE("one"),
TWO("two");
companion object {
// 1st option
fun fromTitle(title: String) {
values().firstOrNull { it.title.equals(title, true) }
}
// 2nd option
private val mapByTitle = Stage.values().associateBy(Stage::title)
fun fromTitle(title: String) = mapByTitle[title.lowercase()]
}
}
which one is better in options?vanshg
05/10/2023, 3:45 PMLiudvikas Sablauskas
05/17/2023, 11:41 AMfun getConfiguration(softwareInformation: SoftwareInformation?, newVersion: Int): Configuration? {
// 1
return when (softwareInformation?.supportsUpdate) {
true -> null
else -> Configuration(version = newVersion)
}
// 2
return if (softwareInformation?.supportsUpdate != true) {
ControllerSoftwareConfiguration(version = newVersion)
} else {
null
}
// 3
return softwareInformation?.supportsUpdate?.takeIf { !it }
?.let { ControllerSoftwareConfiguration(version = newVersion) }
// 4 Some other approach?
}
Chris Fillmore
05/18/2023, 2:57 PMprivate val _myState = MutableStateFlow()
val myState = _myState.asStateFlow()
I have this pattern in many places (using _
prefix for the private member). Anybody have anything they like better?Klitos Kyriacou
06/07/2023, 8:53 AMpublic Foo foo()
, which is known to return non-null but is not annotated as such, what is the preferred way to tell Kotlin that the value you assign is definitely non-nullable? (1) val x: Foo = foo()
or (2) val x = foo()!!
Tara Czutno
07/12/2023, 6:08 PMWhen implementing an interface, keep the implementing members in the same order as members of the interface (if necessary, interspersed with additional private methods used for the implementation).
Is it 1️⃣ interspersed or 2️⃣ all public first? Something else? And does anyone have ktlint or detekt rules to enforce function ordering?
1️⃣ interspersed
class MyClass {
// Constants or properties
private val privateProperty: String = "Private"
// Constructors
constructor() {
// Constructor implementation
}
// Interspersed
fun publicFunction1() {
privateFunction1()
}
private fun privateFunction1() {
// Private function implementation
}
fun publicFunction2() {
privateFunction1()
}
private fun privateFunction2() {
// Private function implementation
}
// Companion object
companion object {
// Companion object members
}
// Overridden functions
override fun toString(): String {
// Overridden function implementation
}
}
2️⃣ all public first
class MyClass {
// Constants or properties
private val privateProperty: String = "Private"
// Constructors
constructor() {
// Constructor implementation
}
// Public functions
fun publicFunction() {
// Public function implementation
}
// Private functions
private fun privateFunction() {
// Private function implementation
}
// Companion object
companion object {
// Companion object members
}
// Overridden functions
override fun toString(): String {
// Overridden function implementation
}
}
diego-gomez-olvera
07/20/2023, 3:09 PMwhen
? I tend to use Unit
but I don't recall if there is an official convention.
enum class Type { A,B,C }
1️⃣
when (type) {
A -> doA()
B -> doB()
C -> Unit // No-op
}
2️⃣
when (type) {
A -> doA()
B -> doB()
C -> {} // No-op
}
I guess that typealias
could be used as well, but it seems overkillMichal Klimczak
08/04/2023, 2:32 PMsealed interface GeneralFormError {
object FieldRequired : GeneralFormError
}
sealed interface SpecificFormError : GeneralFormError {
object PostCodeInvalid : SpecificFormError
}
fun GeneralFormError.message() : String = when(this) {
GeneralFormError.FieldRequired -> "Field is required"
else -> throw IllegalStateException("Subtype of GeneralFormError not handled")
}
fun SpecificFormError.message() : String = when(this) {
SpecificFormError.PostCodeInvalid -> "Post code is invalid"
is GeneralFormError -> (this as GeneralFormError).message()
}
Then I have a variable val postCodeError : GeneralFormError
which can be both FieldRequired
or PostCodeInvalid
. If I call postCodeError.message()
it will throw the ISE. Is there an elegant way of doing this properly (without checking the type in use site).groostav
09/01/2023, 6:25 PMMichal Klimczak
09/07/2023, 10:11 AMecho
09/08/2023, 7:47 AM@ID
of an entity class?
And @Id
property is generated by database autoincrement.
In this question, pk is not-null in the database, and there is discussion within the team about what value should be set as default before Entity persisted, so we are also asking the community's opinion.
In this case, I dont discuss about using constructor each time when create instance.
1. nullable - var
@Entity
class Entity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
)
2. nullable - val
@Entity
class Entity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long? = null
)
3. non-null - var
@Entity
class Entity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = 0L
)
4. non-null - val
@Entity
class Entity(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L
)
Please share your voice and opinion free!Asaf Peleg
09/22/2023, 2:28 AMDeserializer<GenericRecord>
instead of Any
What approaches can I use for that?elect
10/17/2023, 4:22 PM.forEach {
val (k, v) = it.split(':')
meta[k.trim()] = v.trim()
}
I though I could make it more concise with associateTo
, but I still need two lines
.associateTo(meta) {
val (k, v) = it.split(':')
k.trim() to v.trim()
}
unless I'm missing something, I'd revert to the first versionDavid Kubecka
12/01/2023, 3:00 PMmyList.map { transform(it) }
myString.takeIf { it.isNotEmpty() }
As an alternative, however, one could also use function/method references, e.g.
myList.map(::transform)
myString.takeIf(String::isNotEmpty)
Which convention do you prefer and why?christophsturm
12/12/2023, 8:18 AMpackage util
class JsonFetcher() {
...
suspend fun <T> get(url: String, cls: TypeReference<T>): T {
return mapper.readValue(diskCacheHttpClient.get(url), cls)
}
}
suspend inline fun <reified T> JsonFetcher.get(content: String): T = get(content, jacksonTypeRef<T>())
but when I import the helper method I have to import util.get
so its unclear that its the get method of JsonFetcher. is there a way to improve this?Garret Yoder
01/24/2024, 7:18 PMTom Truyen
01/29/2024, 12:34 PMinterface UserRepository
and class UserRepositoryImpl: UserRepository
or
interface IUserRepository
and class UserRepository: IUserRepository
Or are there any alternative practices?Eugen Martynov
02/05/2024, 10:13 AMEugen Martynov
02/05/2024, 10:14 AMGarret Yoder
02/20/2024, 3:26 PMHildebrandt Tobias
03/06/2024, 12:23 PMEndpoints
in my Multiplatform Project so that both js and jvm are always on the same page.
For readability I have a singleton that just holds all the references to the actual Endpoints
.
Is there a more idiomatic way in general to do this or is this fine?
Endpoints.kt
object Endpoints {
// Keycloak
val keyCloakNewToken = _keyCloakNewToken
val keyCloakRefreshToken = _keyCloakRefreshToken
val keyCloakUsers = _keyCloakUsers
// Server
val devices = _devices
val changeDevice = _changeDevice
}
KeyCloakEndpoints.kt
val _keyCloakUsers = Endpoint(
url = "/admin/realms/<realm>/users",
method = EndpointMethod.GET,
serializer = ArraySerializer(KeycloakUser.serializer())
)
val _keyCloakRefreshToken = Endpoint(
url = "/realms/<realm>/protocol/openid-connect/token",
method = <http://EndpointMethod.POST|EndpointMethod.POST>,
serializer = AuthJwt.serializer(),
header = mapOf(
"Content-Type" to "application/x-www-form-urlencoded"
),
requiredUrlEncodedBody = mapOf(
"grant_type" to "refresh_token",
"client_id" to "frontend",
"refresh_token" to ""
)
)
I read that only private Backingfields should start with an underscore, but I can't make them private here of course.Garret Yoder
03/06/2024, 8:09 PM