Michal 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 PMHildebrandt Tobias
03/27/2024, 10:40 AMCzerwinskimarek88
04/17/2024, 8:52 PMclass DoSomethingUseCase {
fun handle(command: DoSomethingCommand) {
TODO("not yet implemented")
}
}
data class DoSomethingCommand(
val someValue: String
)
b) Option B
class DoSomethingUseCase {
fun handle(command: Command) {
TODO("not yet implemented")
}
data class Command(
val someValue: String
)
}
Zyle Moore
05/06/2024, 12:21 AMinline fun Char.toRange(): CharRange =
this..this
@Test
fun `toRange creates a range with a single value`() {
val range = 'Z'.toRange()
assertEquals('Z', range.first)
assertEquals('Z', range.last)
}
Zyle Moore
05/09/2024, 12:32 AMinline fun ByteArray.indicesOf(value: Byte): List<Int> =
mapIndexed { index, byte -> index.takeIf { byte == value } }.filterNotNull()
diego-gomez-olvera
05/13/2024, 11:48 AMPackageNaming
and InvalidPackageDeclaration
, it seems that implicitly the convention is the same, just use lowercaseJørund Amsen
05/14/2024, 2:19 PMfun getAdmins(adminId: String) {
try {
getUsers(adminId)
} catch (e: Exception) {
// "Failed fetching admin by $adminId"
}
}
Now I could wrap the existing exception in a new custom exception MyUserException("Failed ...", e)
However this means I cannot catch the underlying exception specifically, and in most logging tools shows my wrapper rather than the often usefull underlying Exception.
I could rethrow the exception, with a log statement
catch (e: Exception){
log.error("Failed fetching admin...", e)
throw e
}
However I dislike having multiple log entries from a single error, and puts the responsibility on me for "connecting the dots" of the different log statements.George
06/10/2024, 4:39 PMCies
06/11/2024, 4:27 PMif (rank == null) return BadRequest("Rank is missing")
or rank ?: return BadRequest("Rank is missing")
?Thomas
07/16/2024, 6:33 AMfun main() {
val a = A(1)
val b = B(2)
println(b.toA()) //A(a=2)
println(A.fromB(b)) //A(a=2)
}
data class B(val b: Int)
data class A(val a: Int){
//1. "static converter" function
companion object{
fun fromB(b: B): A = A(b.b)
}
}
//2. extension function
fun B.toA() = A(this.b)
Ellen Spertus
08/04/2024, 8:51 PMwidth
(instead of w
) and height
(instead of h
), but those are instance variables in the superclass (JPanel
). I'm a professor creating a problem set, so there aren't team guidelines I can follow. I just want to set a good example.
1️⃣
/**
* Draws a rectangle with the specified [x] and [y] coordinates,
* [outlineColor], and [fillColor]. The parameters [w] and [h]
* specify the width and height.
*/
2️⃣
/**
* Draws a rectangle with width [w] and height [h] with the specified
* [x] and [y] coordinates,[outlineColor], and [fillColor].
*/
Eugen Martynov
09/19/2024, 9:46 AMis String
-> {
0
}
I would expect that closing bracket is on the level of arrow and body had indentation from arrow as well.Ivan Cagle (IvanEOD)
10/06/2024, 10:37 PMopen class TestAbstract {
init {
onCreated()
}
open fun onCreated() {
println("Applying base TestAbstract creation code on class '${this.javaClass.simpleName}'.")
}
}
class Test1 : TestAbstract() {
override fun onCreated() {
super.onCreated()
println("Applying Test1 specific creation code.")
}
}
class Test2 : TestAbstract() {
override fun onCreated() {
super.onCreated()
println("Applying Test2 specific creation code.")
}
}
val test1 = Test1()
val test2 = Test2()
I know this is not encouraged, and the IDE shows a warning for calling onCreated()
in the init
block...
although it seems to work on a simple class... i'm guessing on larger classes with more going on it could cause problems....
I'm curious though... if changing it to the following is just tricking the IDE to make the warning go away, or is it actually acceptable?
open class TestAbstract {
init {
created()
}
private fun created() {
onCreated()
}
open fun onCreated() {
println("Applying base TestAbstract creation code on class '${this.javaClass.simpleName}'.")
}
}
David Breneisen
10/07/2024, 5:35 PMfun BoxScope.MyComposable()
even if the scope isn’t used, the constraint may be helpfulAlexD
11/13/2024, 6:57 PMif (isValidInput) {
doSomething()
doSomethingElse()
} else {
handleInputError()
}
2️⃣
when {
isValidInput -> {
doSomething()
doSomethingElse()
}
else -> handleInputError()
}
Zyle Moore
12/25/2024, 7:33 PM0 Records
, 1 Record
, 2 Records
val recordSummary = listOf(records.size, records.singleOrNull()?.let { "Record" } ?: "Records").joinToString(separator = " ")
val recordSummary = listOf(records.size, if (records.size == 1) { "Record" } else { "Records" }).joinToString(separator = " ")
George Z
12/31/2024, 5:59 PMsuspend fun <T : Any> handleApi(execute: suspend () -> T): Resource<T> {
return try {
val response = execute()
Resource.Success(response)
} catch (e: Exception) {
Resource.Error(
when (e) {
is IOException -> ErrorType.Network
is HttpException -> mapApiError(e.code())
is SerializationException -> ErrorType.Serialization
else -> ErrorType.Unknown
}
)
}
}
2️⃣
suspend fun <T : Any> handleApi(execute: suspend () -> T): Resource<T> {
return try {
val response = execute()
Resource.Success(response)
} catch (e: IOException) {
Resource.Error(ErrorType.Network)
} catch (e: HttpException) {
Resource.Error(mapApiError(e.code()))
} catch (e: SerializationException) {
Resource.Error(ErrorType.Serialization)
} catch (e: Exception) {
Resource.Error(ErrorType.Unknown)
}
}
Roeniss Moon
02/11/2025, 5:46 AMGenerally, avoid using @param and @return tags
But why? Those tags seems useful for converting comments info other formats in my view