Ellen Spertus
05/10/2022, 6:27 PM/**
* Blah blah blah.
* */
Is the close to the comment "`* */`" something you've seen in the wild? The documentation shows "`*/`". https://kotlinlang.org/docs/kotlin-doc.html#generate-the-documentationJonathan Olsson
05/13/2022, 12:45 PMtoString()
for non-debugging/non-logging purposes in a situation like this:
value class AccessToken(private val s: String) {
override fun toString(): String = s
}
val header = "Bearer $accessToken"
Given that inline classes most often wrap primitive-ish types, in my mind it falls into the same category as Long.MIN_VALUE.toString()
. Wdyt?Ellen Spertus
05/14/2022, 9:04 PMfun getSomething(): SomeType {
val result = computeSomething()
doSomethingElse()
return result
}
Vivek Modi
06/01/2022, 2:19 PMEvent
. I want to combine all property value into single string. I did this without any problem. I want to know is there any better way to optimise this code in memory, efficiency etc.
SingleEventString.kt
fun main() {
var newString: String? = null
val eventList = createData()
eventList.forEachIndexed { index, event ->
val title = event.title
val status = event.status
if (!title.isNullOrEmpty()) {
newString = if(index == 0){
"$title"
}else{
"$newString $title"
}
}
if (!status.isNullOrEmpty()) {
newString = "$newString $status"
}
}
println(newString)
}
data class Event(val title: String? = null, val status: String? = null)
fun createData() = listOf(
Event("text 1", "abc"),
Event("text 2", "abc"),
Event("text 3", "abc"),
Event("text 4", "abc"),
Event("", "abc"),
Event(null, "abc")
)Mark
06/02/2022, 2:42 PMtoList()
but then asSequence()
instead of toSequence()
?Klitos Kyriacou
06/16/2022, 4:46 PMpackage companyname.productname.utils
and filename Strings.kt
but I'm looking for something more meaningful, descriptive and idiomatic.vqrs
07/15/2022, 8:39 AMdsl(block: THIS.() -> Unit)
Do you consistently name it *Scope
, *Ctx
or something to that extent?Jonathan Ellis
07/21/2022, 1:40 PM'capitalize(): String' is deprecated. Use replaceFirstChar insteadwhat is the thinking here?
replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() }
is a lot clunkierephemient
07/26/2022, 5:22 PMval range = 1..12; return month in range
), then the compiler does not create the IntRange and produces code equivalent to the firstSlackbot
07/28/2022, 4:02 PMKlitos Kyriacou
08/10/2022, 10:36 AMkotlin.Result
. The project I'm working on currently uses Kotlin 1.6.21, and IDEA 2022.1 tells me "Function returning Result with a name that does not end with Catching". Is this a recommended coding convention? What is the disadvantage of not ending in "Catching"?
Also, when I click on "Show inspection description", it says "Result should never be used as a return type." I know that was the case in an old version of Kotlin, when the Result type was first introduced, but I thought that was now changed and that we can now return Result. Is this something that should be changed in IDEA?Sam Stone
08/12/2022, 8:56 PMGeorge
08/20/2022, 12:13 PMBen Edwards
08/24/2022, 12:07 PM*fun* dropLoot(name: String): Boolean {
*for* (item *in inventory*) {
*if* (item.*name* == name) {
*inventory*.remove(item)
return true
}
}
return false
}
I would do
*fun* dropLoot(name: String): Boolean {
*var* ret = *false*
*for* (item *in inventory*) {
*if* (item.*name* == name) {
*inventory*.remove(item)
ret = *true*
break
}
*return* ret
}
What do people think?sreich
09/01/2022, 6:52 PMsreich
09/12/2022, 6:46 PMisEnabled
convention in java land. i am assuming in kotlin it would just be enabled
, am i correct in this? i can't remember the justification people had for doing that in java, sth to do with properties?George
10/05/2022, 8:45 AMclass ServerError private constructor(val message: String, val code: Int) {
fun <T> toErrorPayload(): HubPayload<T> = errorPayload(message, code)
}
In this case the function toErrorPayload
(for the sake of example ignore the HubPayload return type :)) naming prefix convention shouldBe to
or as
. Since im returning another object i guess the default is to
, but if i want to emphasize that the values remain the same, just the wrapper is changing then should i name it asErrorPayload
? Thanks in advance for any answers !Sam Stone
11/06/2022, 1:31 AMequals
, when should you use if(condition) { return true } else {}
and when should you leave out the else, and use implicit flow control (it is by definition else because it didn’t return). Is there a performance impact in including else
?Ellen Spertus
11/06/2022, 9:53 PMclass WordleGame(val secretWord: String) {
// lots of stuff in here pertaining to a single game of Wordle.
val guesses = mutableListOf<String>()
fun guessWord(guess: String): String {
...
}
}
fun playGame() {
// Load dictionary.
val wordleGame = WordleGame(dictionary.random())
// Solicit guesses from user and feed them to game object, etc.
}
Should playGame()
be in a companion object
in WordleGame
? It certainly would be a handy place to keep the dictionary.Adam Cooper
11/07/2022, 10:39 PMResult
than throw an exception. Is that true in all cases? I've found from my experience in other languages that it's a lot easier to write a REST API with some type of special HTTP status exception that you can throw, which will be handled at the top level and respond appropriately to the client. Should libraries use exceptions? I haven't seen any libraries which return `Result`s.George
11/10/2022, 3:10 PMfun updateOrderQuanity(orderId: OrderId, quantity: Int) {
require(quantity > 0) { "Quantity must be positive" }
val order = loadOrder(orderId)
order.quantity = quantity
storeOrder(order)
}
It is safe to assume that when we are creating a top-level-handler
Dedicate a single top-level place in your code to address all network errors uniformlyHere we actual also refer to
IOExceptions
and IllegalArgumentExceptions
(and any other input/output exceptions)?
Thanks in advance for any answers !Ellen Spertus
11/19/2022, 12:56 AMfilter
, but it seems strange in this situation.
What do you think?Sam Stone
11/23/2022, 5:55 AMif(string !in arrayOf("str1", "str2", "str3"...)) foo()
Option 2:
if(string != "str1" && string != "str2" ...) foo()
Option 3:
when(string) { "str1", "str2", "str3" -> {} else -> foo())
The bytecode for option 3 uses `string`’s hashcode in something like:
label20: {
switch(string.hashCode()) {
case 3541024:
if (string.equals("str1")) {
break label20;
}
break;
case 3541025:
if (string.equals("str2")) {
break label20;
}
break;
case 3541026:
if (string.equals("str3")) {
break label20;
}
}
foo()
}
George
11/30/2022, 2:44 PMSlackbot
12/06/2022, 5:38 AMSeokjae Lee
12/31/2022, 11:19 AMinfix function
?
I wonder what is the officially recommended method, or what is the most used method?
1.
infix fun Class.test(something: Something): Class = this.test(something)
2.
infix fun Class.test(something: Something): Class = test(something)
3.
infix fun Class. test(something: Something): Class { return this. test(something) }
4.
infix fun Class.test(something: Something): Class { return test(something) }
George
01/03/2023, 10:42 AMrunCatching()
does not catch Exception
instead of Throwable
? Shouldn't we always let errors such as StackOverflow
be thrown ?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 bloatiergroostav
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 bloatierephemient
03/15/2023, 10:16 PMcompanion object { operator invoke() }
trick is fine. overall I think it's more common in Kotlin to use
interface Foo
private class FooImpl(...) : Foo
public fun Foo(...): Foo = FooImpl(...)
but that doesn't lead to the same Java APIYoussef Shoaib [MOD]
03/16/2023, 10:12 AMcompanion object operator fun invoke
is definitely idiomatic Kotlin, but yes sometimes people just have a top-level function with the class name. Personally, I think here it makes the most sense to use a companion object so that you get the wanted experience from Java