Vivek Modi
06/10/2022, 10:48 AMval filteredTopics by lazy { MutableStateFlow<List<Topics>>(emptyList()) }
val temp = list.filter { it.topics != null }.filter { it.title == value.title }
filteredTopics.value = temp.firstOrNull()?.topics?.sortedBy { topic -> topic.title } ?: emptyList()
Vivek Modi
06/15/2022, 3:18 PMfun getConsultationCoverageList(): List<ContentWithTitle> {
val list = mutableListOf<ContentWithTitle>()
val consultation = getConsultationItem()
consultation?.consultationCategories?.forEachIndexed { _, consultationCategory ->
val paragraphs = mutableListOf<Paragraph>()
consultationCategory.consultationTopics?.forEachIndexed { _, consultationTopics ->
paragraphs.add(Paragraph(type = LIST_ITEM.type, text = consultationTopics.title))
}
list.add(ContentWithTitle(title = consultationCategory.title, content = Paragraphs(paragraphs), description = consultationCategory.description))
}
return list
}
George
06/17/2022, 7:30 AMpublic interface Payload {
public val data: Any
public val error: Error
}
with factory fun:
public fun <T : Any> Payload(data: T): Payload {
return PayloadImpl(data)
}
public fun errorPayload(error: Error): Payload {
return PayloadImpl(error = error)
}
2️⃣
data class Payload(val data: Any, val error: Error)
Nick Halase
07/06/2022, 6:43 PMval values = listOf("name", "ASC", "description", "DESC")
val propNames = values.filterIndexed { index, _ -> index.mod(2) == 0 }
val sortDirections = values.filterIndexed { index, _ -> index.mod(2) != 0 }
propNames zip sortDirections // [(name, ASC), (description, DESC)]
napperley
07/31/2022, 11:36 PMprivate val runningFunctions: FuncList = mutableListOf()
typealias FuncList = MutableList<Pair<UInt, String>>
internal fun addRunningFunction(pid: UInt, funcName: String) {
runningFunctions += pid to funcName
}
internal fun removeRunningFunction(pid: UInt) {
val list = runningFunctions.filter { it.first == pid }
if (list.size == 1) runningFunctions -= list.first()
}
internal fun listRunningFunctions() = runningFunctions.toList()
// ...
Would the code above be scalable with multiple Coroutines running at the same time?Klitos Kyriacou
08/03/2022, 3:45 PMputAll
on a mutable map, passing it another map and a value transformation function? putAll
allows you to put all entries of another map into this map, but doesn't let you transform them on the fly. mapTo
allows you to transform the entries but you can only write them to a Collection, not to a MutableMap. Is there a method that does what the commented-out line does?
fun main() {
val map1 = mapOf(1 to "one", 2 to "two", 3 to "three")
val map2 = buildMap {
put(4, "fourfour")
put(5, "fivefive")
// map1.mapTo(this) { (k, v) -> k to v + v } DOESN'T COMPILE
// instead we have to use:
putAll(map1.toMutableMap().apply { replaceAll { _, v -> v + v } })
// or:
putAll(map1.map { (k, v) -> k to v + v })
}
println(map2)
}
christophsturm
08/06/2022, 7:37 PMfun <Result> doit(lambda: () -> Result={Unit}) {
}
when the lambda is not passed i want Result to be of type Unit. I get the error Required: Result, found: Unit.iamthevoid
08/09/2022, 6:46 AMfun replaceAlerts(newAlerts: List<ExternalAlert>) {
val data = stateFlow.value
val existsAlerts = data.alerts.toMutableList()
newAlerts.forEach { newAlert ->
for (i in existsAlerts.indices) {
if (newAlert.id == existsAlerts[i].id) {
existsAlerts[i] = newAlert
return@forEach
}
}
existsAlerts.add(newAlert)
}
stateFlow.value = data.copy(alerts = existsAlerts)
}
Jonathan Ellis
08/09/2022, 3:12 PMval flowed = allShapes.map {
var p = it
for (i in 0 until STRETCH_ITERATIONS) {
p = flow(p)
}
p
}
Klitos Kyriacou
08/16/2022, 1:20 PMrateLimiter.acquire()
while (System.nanoTime() < endTime) {
foo()
bar()
baz()
if (System.nanoTime() < endTime)
rateLimiter.acquire()
}
2.
while (true) {
rateLimiter.acquire()
if (System.nanoTime() >= endTime)
break
foo()
bar()
baz()
}
3.
while (run { rateLimiter.acquire(); System.nanoTime() < endTime }) {
foo()
bar()
baz()
}
Travis Griggs
08/16/2022, 6:28 PMoverride fun compareTo(other: NamedObject): Int {
// 5 cases
// we both have null names, compare by oid
// my name is null, his is not, i'm greater (1)
// my name is not null, his is, im less (-1)
// we both have names, compare them
// if names are equal, back to oid
return when {
name == null && other.name == null -> oid.compareTo(other.oid)
name == null && other.name != null -> 1
name != null && other.name == null -> -1
else -> when (val nameCompare = name!!.compareTo(other.name!!)) {
0 -> oid.compareTo(other.oid)
else -> nameCompare
}
}
}
In particular, I was hoping to somehow avoid the !!'s in the middle. I was hoping to somehow invoke the smart pointer thing where it turns green and I don't have to check if it's null after I have previously.Ellen Spertus
08/20/2022, 5:58 PM/**
* Prompts a user for their name and returns their response.
*/
fun getUserName(): String {
println("What is your name? ")
val newName = readln()
return newName
}
/**
* Prints a greeting, using the person's [name].
*/
fun greetUser(name: String) {
println("Hello, $name")
}
/**
* Carries on a brief conversation with a user.
*/
fun converse() {
val name = getUserName()
greetUser(name)
}
KotlinLeaner
09/06/2022, 8:20 PMlet
is going inside the lambda block if value is null. Can someone guide me on this. ThanksEllen Spertus
09/18/2022, 1:25 AMclass USMoney(var dollars: Int, var cents: Int) {
init {
require(dollars >= 0 && cents >= 0)
if (cents >= NUM_CENTS_PER_DOLLAR) {
dollars += cents / NUM_CENTS_PER_DOLLAR
cents %= NUM_CENTS_PER_DOLLAR
}
}
}
I rewrote the code as shown. Is this a good approach and, if so, is there a standard naming convention for the parameters/properties?
class USMoney(_dollars: Int, _cents: Int) {
val dollars = _dollars + _cents / NUM_CENTS_PER_DOLLAR
val cents = _cents % NUM_CENTS_PER_DOLLAR
init {
require(_dollars >= 0 && _cents >= 0)
}
}
christophsturm
09/22/2022, 6:48 AMlog("going to work in items ${items.map {it.id}}")
maybe a way to append directly to the string buffer instead of creating an array.nikolaymetchev
09/23/2022, 10:48 AMclass A {
fun String.hello() {}
}
fun String.hello2() {
A().hello() // cannot find hello()
}
Ellen Spertus
09/26/2022, 1:21 AMclass Person (val personalName: String?, val middleInitial: String?, val familyName: String?) {
override fun toString(): String {
val nameParts = mutableListOf<String>()
if (personalName != null) nameParts.add(personalName)
if (middleInitial != null) nameParts.add(middleInitial)
if (familyName != null) nameParts.add(familyName)
return nameParts.joinToString(separator = " ")
}
}
Ellen Spertus
09/29/2022, 2:19 PMÖmür Kartal - Timewax
10/04/2022, 9:40 AMczuckie
10/08/2022, 5:10 PMList<Byte>
) into a list of Shorts? (List<Short>
) such that [ 0x10, 0x01 ] would become [ 0x1001 ]christophsturm
10/10/2022, 1:27 PMinline fun <reified C> name() = C::class.simpleName
name<Collection<String>>()
this returns “Collection”. is there a way make it return “Collection<String>“?Klitos Kyriacou
10/10/2022, 6:04 PMvar x: Int
var y: Int
do {
x = Random.nextInt(0, NUM_COLS)
y = Random.nextInt(0, NUM_ROWS)
} while (isOccupied(x, y))
place(entity, x, y)
Ellen Spertus
10/11/2022, 1:35 AMEduard Boloș
10/13/2022, 10:49 AMthis::field.isInitialized
considered thread-safe? (field
is a lateinit var
). Trying to figure out if I need to make sure the field gets created from the same thread that it's later accessed from, or if I can just rely on isInitialized
being thread-safe 😄hisham bin awiad
10/17/2022, 8:40 AMprivate fun getCustomEmployeeShifts(
employeeShifts: List<Shifts>?,
approvedOvertimes: List<ApprovedOvertimesModel>?
): List<Shifts> {
val resultList = mutableListOf<Shifts>()
var sh: Shifts
employeeShifts?.forEach { shiftsModel ->
sh = shiftsModel
approvedOvertimes?.forEach { appOverModel ->
if (sh.id == appOverModel.employeeShiftId) {
sh.approvedOvertimes.add(appOverModel)
}
}
resultList.add(sh)
}
return resultList.toList()
}
Paulo Cereda
10/21/2022, 5:25 PMvar
, but I was wondering if there was a way of getting rid of them (just as a personal challenge). Of course, my life would be easier if BreakIterator
could implement Iterable
, but no luck. 😉 Here's the code added for convenience:
fun toGraphemes(str: String) = buildList {
val boundary = BreakIterator.getCharacterInstance()
boundary.setText(str)
var start = boundary.first()
var end = boundary.next()
while (end != BreakIterator.DONE) {
add(str.substring(start, end))
start = end
end = boundary.next()
}
}
Any suggestion is welcome! Thank you! 🦆Andrew Simpson
10/27/2022, 6:32 PMclass Person {
constructor(id: Int, name: String)
constructor(person: Person) : this(person.id, person.name)
}
or would it be “more kotlin-like” to do something like a fun copy() = Person(id, name)
method?Ellen Spertus
11/01/2022, 8:46 PMMob
(abstract), Zombie
, and Spider
. I would like to create a class Spawner<T: Mob>
to create, for example, Spider Spawners (blocks that periodically construct and place new instances of Spider
). I'm trying to figure out the best way to instantiate a new instance of T
from within Spawner<T>
. I tried the following, but it doesn't work because of type erasure:
class Spawner<T: Mob> {
fun spawn() {
val constructor = T::class.constructors.find { it.parameters.isEmpty() } // error: Cannot use 'T' as reified type parameter
val newMob = constructor?.call()
}
}
I'd rather not require the students to create factory classes. (This is an introductory programming class.) Instead I was thinking of faking a factory with a copy()
method:
class Spawner<T: Mob>(val mob: T) {
fun spawn() {
val newMob = mob.copy()
// Place newMob on game board.
}
}
abstract class Mob {
abstract fun copy(): Mob
}
class Pigman: Mob() {
override fun copy() = Pigman()
}
fun main() {
val pigmanSpawner = Spawner<Pigman>(Pigman())
pigmanSpawner.spawn()
}
Something I don't like about this is the type parameter isn't used and could be removed (if I changed the type of the mob
property from T
to Mob
).George
11/09/2022, 5:54 PMrunCatching
in cases where we care about only one type of exception or is this too much neatpicking?
For example:
val result = runCatching { transaction() }
return result.getOrElse {
if (it is IllegalArgumentException) return null else throw it
}
vs
return try {
transaction()
} catch (e: IllegalArgumentException) {
null
}
Thanks in advance for any answers !Marcello Galhardo
11/16/2022, 12:22 AMMarcello Galhardo
11/16/2022, 12:22 AMephemient
11/16/2022, 12:36 AMMarcello Galhardo
11/16/2022, 12:56 AM