Eugen Martynov
05/23/2023, 3:56 PMSmart cast to 'LinkOrigin.ActionButtonLink' is impossible, because 'event.origin' is a public API property declared in different module
LinkOrigin
is sealed class in the different module indeed. But why is it the problem?KotlinLeaner
05/25/2023, 11:37 AMwindowed
for my use case. I tried some code and which is working fine. Is their any possibility to improve this code?
private fun simpleWindowed(unFilteredMovieList: List<NewMovieItem>) {
val filterMovieList = mutableListOf<FilterMovieItem>()
val otherMovieType = mutableListOf<FilterMovieItem>()
unFilteredMovieList
.windowed(size = 2, step = 1, partialWindows = true)
.onEach { window: List<NewMovieItem> ->
val currentItem = window.first()
val nextItem = window.last()
val currentFilterItem = filterItem(currentItem)
if (currentFilterItem != null) {
var seatCount = 0
val screenNumber = nextItem.screenNumber
if (currentItem != nextItem && !screenNumber.isNullOrEmpty()) {
seatCount = getSeatCount(screenNumber)
}
filterMovieList.add(currentFilterItem.copy(seatCount = seatCount))
if (currentFilterItem.type == "other") {
otherMovieType.add(currentFilterItem)
}
}
}
filterMovieList.onEach { println(it) }
println("---------------")
otherMovieType.onEach { println(it) }
}
More code in thread to understand the basic logicchanjungskim
06/02/2023, 6:23 AMGrigory Panko
06/05/2023, 3:14 PMSam Stone
07/11/2023, 9:13 AMtime.isNaN()
, or some special value like Date.from(Instant.MIN)
?
/**
* A method that returns a [Date] from the time passed in as a parameter.
*
* @param time
* The time to be set as the time for the `Date`. The time expected is in the format: 18.75
* for 6:45:00 PM.time is sunrise and false if it is sunset
* @param isSunrise true if the
* @return The Date.
*/
protected fun getDateFromTime(time: Double, isSunrise: Boolean): Date? {
if (time.isNaN()) {
return null
}
var calculatedTime: Double = time
val adjustedCalendar: Calendar = adjustedCalendar
val cal: Calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal.clear() // clear all fields
cal[Calendar.YEAR] = adjustedCalendar[Calendar.YEAR]
cal[Calendar.MONTH] = adjustedCalendar[Calendar.MONTH]
cal[Calendar.DAY_OF_MONTH] = adjustedCalendar[Calendar.DAY_OF_MONTH]
val hours = calculatedTime.toInt() // retain only the hours
calculatedTime -= hours.toDouble()
// retain only the minutes
calculatedTime *= 60
val minutes = calculatedTime.toInt()
calculatedTime -= minutes.toDouble()
// retain only the seconds
calculatedTime *= 60
val seconds = calculatedTime.toInt()
calculatedTime -= seconds.toDouble() // remaining milliseconds
// Check if a date transition has occurred, or is about to occur - this indicates the date of the event is
// actually not the target date, but the day prior or after
val localTimeHours = (geoLocation.longitude / 15).toInt()
if (isSunrise && localTimeHours.plus(hours) > 18)
cal.add(Calendar.DAY_OF_MONTH, -1)
else if (!isSunrise && localTimeHours.plus(hours) < 6)
cal.add(Calendar.DAY_OF_MONTH, 1)
cal[Calendar.HOUR_OF_DAY] = hours
cal[Calendar.MINUTE] = minutes
cal[Calendar.SECOND] = seconds
cal[Calendar.MILLISECOND] = (calculatedTime * 1000).toInt()
return cal.time
}
Sam Stone
07/16/2023, 9:03 PMsuspend fun getValue(): String = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
if(condition) {
return@withContext CONST
} else {
if(disk.readValueFromDisk() == "") {
val newValue = Generator.generateValue().toString()
disk.writeValueToDisk(newValue)
}
return@withContext disk.readValueFromDisk()
}
}
B:
suspend fun getValue(): String = if(condition) CONST else withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
disk
.readValueFromDisk()
.takeIf { it.isNotEmpty() }
?: Generator
.generateValue()
.toString()
.also {
disk.writeValueToDisk(it)
}
}
Asad Mukhtar
07/18/2023, 8:13 PMclass ViewModel {
private val _password = MutableStateFlow<String>("")
val password: StateFlow<String> = _password
fun onPasswordChanged(password: String) {
_password.value = password
}
}
@Composable
fun Screen() {
val viewModel = remember { ViewModel() } // or viewModel() etc.
val password by viewModel.password.collectAsState()
TextField(
value = password,
onValueChange = viewModel::onPasswordChanged
)
}
Second Option:
class MutableStateAdapter<T>(
private val state: State<T>,
private val mutate: (T) -> Unit
) : MutableState<T> {
override var value: T
get() = state.value
set(value) {
mutate(value)
}
override fun component1(): T = value
override fun component2(): (T) -> Unit = { value = it }
}
@Composable
fun <T> MutableStateFlow<T>.collectAsMutableState(
context: CoroutineContext = EmptyCoroutineContext
): MutableState<T> = MutableStateAdapter(
state = collectAsState(context),
mutate = { value = it }
)
class ViewModel {
val password = MutableStateFlow("")
}
@Composable
fun Screen() {
val viewModel = remember { ViewModel() } // or viewModel() etc.
val (password, setPassword) = viewModel.password.collectAsMutableState()
TextField(
value = password,
onValueChange = setPassword
)
}
KotlinLeaner
07/25/2023, 12:30 PMprivate const val BOLD_PATTERN = "<b>(.*?)</b>"
fun main() {
val message = "Hello, How are you? My Name is <b>Xyz</b>. <b>Abc</b> your next score will be 100 to win the game."
val itemList = findAndGetBoldList(message)
val filterMessage = message.replace("<b>", "").replace("</b>", "")
itemList.forEach { println("Bold part is :- $it") }
println(filterMessage)
}
fun findAndGetBoldList(message: String): List<String> {
return BOLD_PATTERN
.toRegex()
.findAll(message)
.map {
it.value.replace("<b>", "").replace("</b>", "")
}
.toList()
}
chanjungskim
07/31/2023, 12:38 AMEmre
08/04/2023, 9:33 PMsuspend
function or should I incorporate the coroutine scope into the function and eliminate the suspend
? If the caller itself is a suspend
I’d go with the former but I’m not decided if it is not.
edit: Answered in #coroutinesSam Stone
10/05/2023, 11:38 PMDegreeOffset.NINETEEN_POINT_EIGHT_DEGREES
so often. However, it is illegal to write DegreeOffset.19.8
, and I don't want to resort to `DegreeOffset.`19.8``. What is the best language construct/naming convention to use, and should this become a feature request for one? DegreeOffset._19_8
maybe? Looks wrong.stoyicker
10/26/2023, 1:17 PMprivate fun <T> runInTheFutureButAlsoWaitForResult(block: Foo.() -> T): T {
var ret: T? = null
var done = false
val condition = reentrantLock.newCondition()
someOtherThread.runAtSomePointInTheFuture {
ret = delegate.block()
done = true
reentrantLock.withLock { condition.signal() }
}
reentrantLock.withLock {
while (!done) {
condition.await()
}
}
return ret as T
}
While this does work at runtime for both cases in which T is nullable and non-nullable, casting ret to T is marked as unsafe, which does make sense, but if I define ret as type T, I can't assign null to it, which makes sense too, but I also can't assign anything else because I don't know what T is so I can't instantiate it. Therefore, I could try to make it lateinit, but mind you, lateinit can't be used with types whose upper bound is nullable, as is the case implicitly for T. Is there a way to write this code "correctly"?Mark
11/01/2023, 8:38 AMFlow
extension fun (taken from here) for collecting single shot events (Android):
@Suppress("ComposableNaming")
@Composable
fun <T> Flow<T>.collectInLaunchedEffectWithLifecycle(
vararg keys: Any?,
lifecycle: Lifecycle = LocalLifecycleOwner.current.lifecycle,
minActiveState: Lifecycle.State = Lifecycle.State.STARTED,
collector: suspend CoroutineScope.(T) -> Unit
) {
val flow = this
val currentCollector by rememberUpdatedState(collector)
LaunchedEffect(flow, lifecycle, minActiveState, *keys) {
withContext(Dispatchers.Main.immediate) {
lifecycle.repeatOnLifecycle(minActiveState) {
flow.collect { currentCollector(it) }
}
}
}
}
LeoColman
11/09/2023, 9:56 PMsealed class IssueStatus(
val transitionsTo: List<IssueStatus>
) {
constructor(vararg transitionsTo: IssueStatus) : this(transitionsTo.toList())
data object Closed : IssueStatus()
data object Acknowledged : IssueStatus(New, Closed)
data object New : IssueStatus(Acknowledged, Closed)
}
How would you solve this issue?
References inside transitionsTo
are null, as they're referencing before it's been declaredstantronic
11/15/2023, 10:47 AMfun MyClass.Companion.create()
what is best to call the file? MyClassCreate.kt
/ MyClass_create.kt
stantronic
11/15/2023, 10:48 AMMark
11/16/2023, 8:09 AM@Composable
fun LayoutItemsVerticallyWrappingFirstWidth(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(
content = content,
modifier = modifier,
) { measurables, constraints ->
val firstItem = measurables.firstOrNull()
?: return@Layout layout(
width = constraints.minWidth,
height = constraints.minHeight,
) { }
val firstItemWidth = firstItem.maxIntrinsicWidth(constraints.maxHeight)
val itemConstraints = Constraints(
minWidth = 0,
minHeight = 0,
maxWidth = firstItemWidth,
maxHeight = constraints.maxHeight,
)
val placeables = measurables.map { measurable ->
measurable.measure(itemConstraints)
}
val height = placeables
.sumOf(Placeable::height)
.coerceAtMost(constraints.maxHeight)
layout(width = firstItemWidth, height = height) {
var yOffset = 0
placeables.forEach { placeable ->
val xOffset = (firstItemWidth - placeable.width) / 2
placeable.place(xOffset, yOffset)
yOffset += placeable.height
}
}
}
}
Daniel Pitts
11/18/2023, 2:03 AMval openFileAction = action(name = "Open", icon = openIcon) {
showOpenDialog()
}
// etc...
with(JFrame()) {
createMenuBar {
menu("File") {
item(action = openFileAction)
// etc...
}
addSeparator()
menu("Edit") {
item(action = undoAction)
item(action = redoAction)
addSeparator()
item(action = deleteAction)
// etc...
}
}
}
Ellen Spertus
11/27/2023, 1:39 AMCollection
are the same, if nothing is known about the concrete type? Here are some ideas:
val c: Collection<Int> = ??
// This may do more work than necessary.
println(c.toSet().size == 1)
// This requires converting the collection to a list.
val list = c.toList()
println(list.all { it == list[0] })
Daniel Pitts
12/20/2023, 2:21 AMclass Else<R> private constructor(private val value: Any?) {
infix fun `else`(alternative: () -> R): R =
if (value == IsNot) alternative() else value as R
companion object {
private object IsNot
fun <R> `is`(value: R) = Else<R>(value)
fun <R> `isn't`() = Else<R>(IsNot)
}
}
fun <R> `if`(condition: Boolean, value: () -> R) = if (condition) Else.`is`(value()) else Else.`isn't`()
Daniel Pitts
01/14/2024, 11:04 PMelect
02/15/2024, 10:01 AMval tuples = receiveText()
.drop(1).dropLast(1)
.split(',')
.map { it.substringBefore(':') to it.substringAfter(':') }
to transform something like this
{"event_type":"pre-commit","event_time":"2024-02-15T095148Z","action_name":"Dataset","hook_id":"dataset_validator","repository_id":"quickstart","branch_id":"main","source_ref":"main","commit_message":"asd","committer":"quickstart"}into a
List<Pair<String, String>>
?dave08
02/15/2024, 5:02 PMKev
02/16/2024, 2:42 AM.map(::MyDto)
or .map(::println)
?KotlinLeaner
02/17/2024, 3:55 PMdave08
02/21/2024, 11:52 AMCLOVIS
02/26/2024, 2:48 PMisRunning = result != null && result.isActive
isRunning = !(result == null || !result.isActive)
Zsolt.bertalan
03/04/2024, 3:18 PMVivekpanchal64
03/11/2024, 10:46 AMelect
03/14/2024, 9:43 AMfor (lib in listOf("gluegen:gluegen-rt", "jogl:jogl-all"))
for (platform in listOf("linux-aarch64", "linux-amd64", "linux-armv6hf", "linux-i586",
"macosx-universal", "windows-amd64", "windows-i586"))
"org.jogamp.$lib-natives-$platform"
I came out with this
val libs = listOf("gluegen:gluegen-rt", "jogl:jogl-all")
val platforms = listOf("linux-aarch64", "linux-amd64", "linux-armv6hf", "linux-i586", "macosx-universal", "windows-amd64", "windows-i586")
platforms.flatMap { p -> libs.map { "org.jogamp.$it-natives-$p" } }