Hullaballoonatic
11/29/2019, 5:57 PMfun <K, V> Array<K>.associateWith(valueSelector: (K) -> V): Map<K, V>
why is this not in stdlib already? i'm very confused.
all other versions of associate from Iterable
exist on Array
except this one.
my use case:
myEnumClass.values().associateWith { ... }
Hullaballoonatic
12/04/2019, 5:07 PMfold
and reduce
have foldRight
, reduceRight
, I would like windowedRight
and chunkedRight
. My current use case is also maybe the best example:
val Int.digitBlocks get() = toString().chunkedRight(3).map(String::toInt) // 1_234_567 -> [[567], [234], [1]]
I noticed CharSequence
also has a version of windowed
that accepts a transform operation, and I would like that for Iterable
as well.
In general why don't most Iterable operations also have a version with a transform operation tacked on? I don't think that hurts readability, and only partially conflicts in places where the operation already receives a lambda, like partition
Leon K
12/05/2019, 4:40 PMrequire
that allow for specifying a custom Exception type to throw, instead of just throwing IllegalArgumentException
asad.awadia
12/05/2019, 8:39 PMXavier F. Gouchet
12/06/2019, 10:05 AMoperator fun Char.times(i: Int): String {
check(i >= 0) { "Can't repeat character negative times " }
return String(CharArray(i) { this })
}
val s = '_' * 8
jimn
12/07/2019, 4:58 PMLeoColman
12/10/2019, 8:41 PMString?.isNullOrBlank()
but there is no String?.isNotNullOrBlank()
while there is a String.isBlank()
and String.isNotBlank()
Simon Schubert
12/12/2019, 12:06 PMvar ids = listOf("123", "456", ...)
var imageUrl = getFirstImageUrl(ids)
fun getFirstImageUrl(list: List<String>): String? {
list.forEach {
var item = database.getItemById(it)
if(item != null) {
return item.imageUrl
}
}
return null
}
Is there a better way to do it in kotlin? I could image a solution something like this:
var imageUrl = ids.firstNotNullFlat {
var item = database.getItemById(it)
item?.imageUrl
}
Leon K
12/14/2019, 11:00 AMif(foo != null)
for multiple values and collection contents.
Proposal part one
add a ifNotNull
function that takes vararg arguments of type Any?
.
given
val a: Int? = 1
val b: String? = null
val c: Boolean? = false
this would allow to replace this:
if (a != null && b != null && c != null) {
println("$a, $b, $c")
}
with this:
ifNotNull(a, b, c) {
println("$a, $b, $c")
}
which imo is a lot more readable, and also easier to type.
(small note/question: would these checks - if the function was just implemented in terms
of contracts and the if-statement - short-circuit, like they do with the
if-statement?)
proposal part two
higher-order-functions on collections should do smart-casting. (I guess this should be doable via contracts?)
given
fun useList(nums: List<Int>) = println(nums)
val foo: List<Int?> = listOf(12, 13, null, 14)
this would allow to do something like this:
if (foo.all { it != null } ) {
useList(foo)
}
currently, afaik, this check is not possible with compiler-guarantees, as there
is no Collection<T>.hasNoNulls()
check.
there are some simmilar functions, but nothing that actually does this.
there is
- Iterable<T?>.requireNoNulls()
- the most simmilar, but this throws
exceptions and isn't as general as making all
and any
-calls smart-cast
- Iterable<T?>.filterNotNull()
- could be currently used in combination with
the all-check to "simulate" a smart-casting all, but as it just filters out the
null-values, this could to easily be broken if someone isn't careful when
modifiying the preceding if-statement.jimn
12/15/2019, 10:19 AM"string".size
unreasonable as a stdlib feature?dave08
12/15/2019, 2:00 PMtoTypedArray
on a Sequence
?Sujit
12/18/2019, 12:58 AMclass TooManyMembers(
val mem1: Int? = null,
val mem2: Int? = null,
.
.
.
val mem248: Int? = null) {
}
That's a class with 248 members. Instantiating this member with val obj = TooManyMembers()
throws this error at runtime:
Too many arguments in method signature in class file SerializationTests$TooManyMembers
java.lang.ClassFormatError: Too many arguments in method signature in class file SerializationTests$TooManyMembers
If I remove just one member, no more of that error. Is that really a limit (247) with numbers of members one can have in a kotlin class? What can I do if I have an object with more members? 247 seems way too low. This is with kotlin 1.3.61
Marc Knaup
12/24/2019, 12:00 PM.toList()
, .map()
, .filter()
, listOf()
, etc. use some immutable List
subclass internally, so that subsequent calls to .toList()
don’t have to create another copy? 🙂
Would be great for defensive copy patterns, since you don’t know whether the list you get is immutable or not.Marc Knaup
12/24/2019, 4:23 PMMap.getOrElseNullable()
not public API?
I’ve just now noticed that .getOrElse()
doesn’t work as documented for null
values.
Returns the value for the given key, or the result of thefunction if there was no entry for the given key.defaultValue
jimn
01/05/2020, 8:44 AM(LocalDate.MAX t2 LocalDate.MIN)
except with some keyboard practice for each of the primitive types getting thier own minmax
2. related to existing keyboard practice: min and max don't want to behave in intellij with a generic syntax and it's hard to guess the intent of max`Of` vs. max, min`Of` vs. min -- since they both evaluate on pairs where list`Of` for instance operates on vararg<T>
3. i distrust an immutable loop return where an array of two mutable values might have more mechanical sympathy
fun feature_range(seq: Sequence<LocalDate>):Pair</**min*/LocalDate,/**max*/LocalDate> = seq.fold(LocalDate.MAX to LocalDate.MIN) { (a, b), localDate ->
minOf(a, localDate) to maxOf(b, localDate)
}
gregorbg
01/08/2020, 7:06 PMMap<K, List<V>>
into a Map<V, K>
such that every entry in the List<V>
becomes associated with its original key K
? ({"foo": [1, 2, 3]}
becomes {1: "foo", 2: "foo", 3: "foo"}
)Xavier F. Gouchet
01/09/2020, 10:53 AMclamp
method on Numbers in the StdLib :
fun clamp(d: Double, min : Double, max : Double) : Double {
return if (d < min) {
min
} else if (d > max) {
max
} else {
d
}
}
or
fun Double.clamp(min : Double, max : Double) : Double {
return if (this< min) {
min
} else if (this > max) {
max
} else {
this
}
}
Zac Sweers
01/10/2020, 7:59 AMtypeOf()
for mutable collections just returns the immutable type?Zac Sweers
01/10/2020, 8:07 AMbbaldino
01/13/2020, 6:17 PMtypeOf
?asad.awadia
01/15/2020, 12:05 AMMark
01/17/2020, 6:05 AMinner class
I can access it normally from outside of that class and containing class. But if I move that function out of inner class (but still inside the containing class) and make it an extension fun of the inner class, then I cannot access it in the same way - instead I need to do with(instanceOfContainingClass)
Why the difference?gcx11
01/18/2020, 12:53 PMinline fun <T, C: MutableCollection<T>> MutableList<T>.retrieveAllTo(collection: C, predicate: (T) -> Boolean): C {
val iterator = this.listIterator()
for (item in iterator) {
if (predicate(item)) {
collection.add(item)
iterator.remove()
}
}
return collection
}
inline fun <T> MutableList<T>.retrieveAll(predicate: (T) -> Boolean): List<T> {
return mutableListOf<T>().also { retrieveAllTo(it, predicate) }
}
Kiryushin Andrey
01/21/2020, 1:29 PMIEnumerable
interface and its extension methods behave like the ones for Sequence
- that is, they are evaluated lazily, processing items from the source one by one. Therefore in C# any LINQ method applied to a collection starts a chain of lazy methods operating on IEnumerable
and we use ToList
in the end if a materialized collection is needed as a result of the pipeline. In Kotlin, then, not only the lazy to eager transition should be done explicitly (by calling toList
) but also an eager to lazy one (by calling asSequence
). Is this explicitness the purpose of existing separate Sequence
and Iterable
interfaces? Why is this explicitness in going from eager to lazy evaluation needed? Or does it have something to do with the fact that Iterable
comes from Java and has been therefore in some way not suitable for lazy evaluations?
• I also had a glimpse of streams in Java. Am I right that conceptually this is the same as Sequence
in Kotlin, so that Sequence
should be used everywhere unless Java interop is required? Are there some advantages of streams over sequences or sequences over streams besides those imposed by the fact that one comes from Kotlin and the other from Java?wasyl
01/24/2020, 2:14 PMasad.awadia
02/01/2020, 3:48 PMjimn
02/07/2020, 5:53 AMA.(B)->C
when i came upon a random refactoring intent having reverted it after testing it and seeing it worked all the same. https://kotlinlang.org/docs/reference/lambdas.html#function-literals-with-receiver as it turns out is a real thing.
so there are a few quirks about stdlib, gaps between say list and array which appeear to be interchangable but are not(unless i write them). and likewise for the primitive arrays and the object arrays.
is there an undercurrent of some java-generics like algebra that spoils it for writing a suite of generic extensions for the existing base kotlin libs?Marc Knaup
02/07/2020, 7:36 AM.ifNull { … }
would be awesome indeed :)
https://kotlinlang.slack.com/archives/C0B8Q383C/p1481236430000013
?:
requires weird brace positioning and makes functional code less readable.
inline fun <T : Any> T?.ifNull(onNull: () -> T): T {
contract {
callsInPlace(onNull, InvocationKind.AT_MOST_ONCE)
}
return if (this !== null) this else onNull()
}
elect
02/07/2020, 7:45 AMpublic fun <T> compareBy(vararg selectors: (T) -> Comparable<*>?): Comparator<T>
but the descending counterpart is missingMarc Knaup
02/07/2020, 8:28 AMkotlin.Number
, which unfortunately is an abstract class.Marc Knaup
02/07/2020, 8:28 AMkotlin.Number
, which unfortunately is an abstract class.elect
02/07/2020, 1:43 PMinterface
if possibleZach Klippenstein (he/him) [MOD]
02/07/2020, 3:23 PM