nkiesel
12/28/2022, 12:50 AMchunked
(or chunkedBy
) which takes a predicate instead of an Int? Something like
fun <T> List<T>.chunkedBy(predicate: (T) -> Boolean): List<List<T>> =
fold(mutableListOf(mutableListOf<T>())) { acc, item ->
if (predicate(item)) {
acc.add(mutableListOf())
} else {
acc.last().add(item)
}
acc
}
Zoltan Demant
12/29/2022, 1:57 PMinline val
actually make a difference?
inline val ButWhy get() = "?"
val Difference get() = "?"
kevin.cianfarini
01/05/2023, 2:38 AMstatx
system call defines a bitmask for attributes of a file you'd like to get. I've come up with the following abstraction around this but am not pleased with it because it requires an additional allocation.
public value class FileStatusRequest internal constructor(internal val bitMask: UInt)
@FileRequestDsl public class FileStatusRequestBuilder internal constructor() {
private var bitMask: UInt = 0u
public fun requestFileSize() { bitMask = bitMask or STATX_SIZE }
public fun requestBlocksOccupied() { bitMask = bitMask or STATX_BLOCKS }
public fun build(): FileStatusRequest = FileStatusRequest(bitMask)
}
Swift has the OptionSet
protocol which could abstract bitmask operations quite nicely. A Kotlin equivalent might look like the following.
value class FileStatusRequest(internal var bitMask: UInt) : OptionSet<FileStatusTrait> {
override fun insert(trait: FileStatusTrait) { bitMask = bitMask or trait.statxMask }
override fun remove(trait: FileStatusTrait) { bitMask = bitMask and trait.statxMask.inv() }
}
enum class FileStatusTrait(internal val statxMask: UInt) { ... }
Has the stdlib team considered something like OptionSet
as a means of wrangling (mainly) bitmasks?mcpiroman
01/10/2023, 1:48 PMInt
, UInt
, Long
, Short
, Float
, Double
2️⃣ Rust-like: I32
, U32
, I64
, I16
, F32
, F64
3️⃣ Mixed: Int32
, UInt32
, Int64
, Int16
, Float32
, Float64
🧵 Other?homchom
01/11/2023, 5:32 AMList.of
IntelliJ warns me that it "should be replaced with [the] Kotlin function" listOf
. If I understand correctly, these two functions are actually very different; is there something I am missing? Is this a false positive?mattinger
01/11/2023, 5:26 PMcopy
and destructuring functions which can cause backward compatibility issues in libraries.Rob Elliot
01/16/2023, 6:01 PMList<T>.take(n: Int): List<T>
only Iterable<T>.take(n: Int): List<T>
which constructs a new ArrayList and copies elements in.
Wouldn't this be more efficient on a List, as it could just return a view?
fun List<T>.take(n: Int): List<T> = subList(0, n)
(And of course the same for drop
)kevin.cianfarini
01/18/2023, 7:17 PMOpenEndRange
and I’d like to understand the rational for why ComparableOpenEndRange.equals
specifically checks if the other
instance is ComparableOpenEndRange
.
override fun equals(other: Any?): Boolean {
return other is ComparableOpenEndRange<*> && (isEmpty() && other.isEmpty() ||
start == other.start && endExclusive == other.endExclusive)
}
My use case is that I have a custom implementation of OpenEndRange<LocalDateTime>
which I want to be equitable against ComparableOpenEndRange
. My implementation of equals checks for this
override fun equals(other: Any?): Boolean = when (other) {
is LocalTimePeriod -> other.start == start && other.timeZone == timeZone && other.duration == duration
is OpenEndRange<*> -> other.start == start && other.endExclusive == endExclusive
else -> false
}
And therefore equality checking works when my implementation is on the left side of the ==
operator. However when a comparable open range is on the left hand side of the operator, because my custom impl is not an instance of ComparableOpenEndRange
, the equality check fails.
I believe this is an oversight in the stdlib but I’m wondering if this is by design? If so, what is the rationale?Yacov Rosenberg
01/20/2023, 6:15 PMfun DownloadManager.isAudiobookCompleted(isbn: String): Boolean {
return currentDownloads
.filter { it.audiobookIsbn == isbn }
.all { it.state == Download.STATE_COMPLETED }
}
Very intuitive where I want to return true, but was buggy. So I went to see why and just realized how the .all works:
/**
* Returns `true` if all elements match the given [predicate].
*
* @sample samples.collections.Collections.Aggregates.all
*/
public inline fun <T> Iterable<T>.all(predicate: (T) -> Boolean): Boolean {
if (this is Collection && isEmpty()) return true
for (element in this) if (!predicate(element)) return false
return true
}
Basically when the list isEmpty, it returns true. Is't it wrong?
I mean, for me it should return true only match the predicate, and if the list is empty for sure don't match the predicate...Leon Linhart
01/25/2023, 4:48 PMelect
01/26/2023, 8:40 AMremoveLast
on ArrayList
?Mikael Ståldal
01/31/2023, 10:09 AMmyList.groupingBy { it }.eachCount().toList().sortedBy { it.second }
Is there any shorter and/or more efficient way of doing this? Maybe some shortcut for groupingBy { it }
?elect
02/02/2023, 9:10 AMRange
on enums?Marcin Wisniowski
02/07/2023, 5:09 PMdata class A(val b: B)
, and a Comparator<B>
, how can I sort the list with this comparator? sortedWith()
won’t work because the comparator type doesn’t match. sortedBy()
allows me to select the inner value b
, but then doesn’t let me choose my comparator.natpryce
02/07/2023, 10:40 PM(1 .. 10 step 2)
returns an IntProgression, ('a' .. 'z' step 2)
returns a CharProgression, and there are equivalents for many built in types, but not for user-defined types.
Could the stdlib define the step
function for ClosedRange<T>
, to return a new stdlib type Progression<T>
.?denis090712
02/13/2023, 11:02 AMfun <K, V> SortedMap<K, V>.take(count: Int): SortedMap<K, V> {
if (size <= count) return this
val found = keys.elementAt(count)
return headMap(found)
}
also, it is possible to implement drop
function in the same fashion
My case was to take a snapshot of the original tree of depth N.diego-gomez-olvera
02/21/2023, 5:21 PMpublic static boolean isEmpty(@Nullable CharSequence str) {
return str == null || str.length() == 0;
}
And I would like to deprecate it for Kotlin users. I can change it to use an stdlib function
@JvmStatic
@Deprecated("Use `isNullOrEmpty`", replaceWith = ReplaceWith("str.isNullOrEmpty()"))
fun isEmpty(str: CharSequence?): Boolean = str.isNullOrEmpty()
and it will warn Kotlin users and guide them towards the stdlib function, however it will also show as @deprecated
for Java, where it is still needed (isNullOrEmpty
is InlineOnly
). Is it possible to show as deprecated only for Kotlin?Zoltan Demant
02/22/2023, 10:55 AMkotlin.time.Duration
? I thought this would be simple (it probably still is) but my first attempt didnt result in the behavior I was expecting, and Im not 100% clear on why that is (code for that in 🧵).
fun round(
duration: Long,
period: Long = 1000,
): Long {
val half = period / 2
return (duration + half) / period * period
}
eygraber
03/03/2023, 1:15 AMArray.sliceArray
return a view on the original array, and if not, is there a way to do that?Marco Pierucci
03/06/2023, 4:24 AMdriveActivities = drivingActivities.toImmutableList()
The compiler complains because toImuutableList()
return a List
I can use driveActivities = drivingActivities.toPersistentList()
but it somehow feels like I'm leaking Impl details?Peter
03/07/2023, 12:27 PMfun <T> MutableCollection<T>.addNotNull(elem: T?): Boolean {
return if (elem !== null) add(elem) else false
}
I find it keeps my code more clean than all the if (elem !== null) { collection.add(elem) }
boilerplate statements. I was always surprised it doesn’t come with stdlib already (or I couldn’t find it).napperley
03/07/2023, 10:55 PMDaniele B
03/09/2023, 12:20 AMnapperley
03/09/2023, 1:25 AMMichal Klimczak
03/09/2023, 7:35 AM@Deprecated
with ReplaceWith
, but it doesn't use all the imports. One of the imports is related to the expression used in ReplaceWith, the other is added for a top level extension function which would retrofit the old deprecated usage. But the other one is not automatically included by IDE, when replacing.
Is that by design or am I encountering some bug?Mark
03/11/2023, 5:20 AMinline fun <reified T: Enum<T>> Foo.enumBar(name: String): Bar<T?> = this.propertyToHide.toBar(name)
Mark
03/11/2023, 8:30 AMFooWrapper
(which is allowed) and FooWrapper
already extends Foo
?
sealed interface Foo
interface FooWrapper: Foo {
val wrappedFoo: Foo
}
// other module
class FooWrapperImpl(
override val wrappedFoo: Foo,
): FooWrapper, Foo by wrappedFoo // Inheritance of sealed classes or interfaces from different module is prohibited
Youssef Shoaib [MOD]
03/24/2023, 1:16 PMforEachWithNext
, analogous to zipWithNext
. Could be a nice addition to stdlib. Here's an impl based on `zipWithNext`:
inline fun <T> Iterable<T>.forEachWithNext(block: (a: T, b: T) -> Unit) {
val iterator = iterator()
if (!iterator.hasNext()) return
var current = iterator.next()
while (iterator.hasNext()) {
val next = iterator.next()
block(current, next)
current = next
}
}
yschimke
03/24/2023, 8:58 PMPHondogo
03/31/2023, 6:03 AM