amit
04/11/2020, 2:05 PMbjonnh
04/15/2020, 7:28 PMAlanna
04/28/2020, 9:21 PM.equals()
instead of ==
, the two of which give me a different results.
>>> 0f == -0f
res0: kotlin.Boolean = true
>>> 0f.equals(-0f)
res0: kotlin.Boolean = false
>>> listOf(0f) == listOf(-0f)
res1: kotlin.Boolean = false
The best way I've come up with to solve this is by defining my own assertEquals function that works on List<Float>, but this doesn't seem very clean to me. Is there a better way to do this? Also, why doesn't list equality use ==
?Aslam Hossin
05/05/2020, 4:54 AMoverride fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
if (context is Listener) {
listener = context
}
}
override fun onDetach() {
super.onDetach()
listener = null
}
elect
05/19/2020, 1:02 PMreturn
(short and elegantly)?
fun getArgCount(): Int {
when (lastToken) {
null -> return 1
is Token.OpenParentheses, is Token.ArgumentSeparator -> {
return 1
}
else -> (lastToken as? Token.Operator)?.operator?.let { lastOp ->
if (lastOp.numOperands == 2 || lastOp.numOperands == 1 && !lastOp.isLeftAssociative)
return 1
}
}
return 2
}
Tuang
05/22/2020, 9:46 AMfun A(infoA: Info, conn: Connection, userId: Int): Result {
val overSettingOfA: OverSetting = AppSetting.instance.retrieveA(infoA, conn, userId)
// some code
return Result(overSettingOfA)
}
fun B(infoB: Info, conn: Connection, userId: Int, someInfo: SomeInfo): Result {
val overSettingOfB: OverSetting = AppSetting.instance.retrieveB(infoB, userId, conn, someInfo)
// some code
return Result(overSettingOfB)
}
Both of fun A
and fun B
have the same logic, what they are doing is all the same. I m trying to do likes high order function but the problem is
the argument is not the same, fun A
has 3 arg and fun B
has 4.
Is there any a magical way? 😀JP
05/24/2020, 10:51 AMEugen Martynov
05/28/2020, 9:25 AMabstract class A {
abstract fun doSomething()
}
with
object: A() {
override fun doSomething(){}
}
or
class A(private val doSomething: () -> Unit)
with
A() {...}
?vaskir
06/19/2020, 12:29 PMval last = (0..3).flatMap { x ->
(0..3).map { y ->
offsets.sumBy { (first, second) ->
arr[y + second][x + first]
}
}
}.max()
arekolek
06/25/2020, 2:26 PM.filter { it }
or
2️⃣
.filter(true::equals)
andyg
06/28/2020, 8:18 PMdata class counters(var small: Int, var big: Double)
fun Int.add3() : Int = this + 3 // accepts Int, returns Int
fun Double.times2pt5() : Double = this * 2.5
fun main() {
val mycounters : counters = counters(4, 201.0)
mycounters.small.apply{ this.add3() }
mycounters.apply { this.big.times2pt5() }
println(mycounters) // prints 4, 201.0 -- same as original
val uglyCounters : counters = counters(6, 401.0)
uglyCounters.apply {
this.small = this.small.add3()
this.big = this.big.times2pt5()
}
println(uglyCounters) // works, prints 9, 1002.5, but is ugly
}
Jakekudur
07/02/2020, 4:39 AMPhilipp Mayer
07/08/2020, 10:11 AMval newSmth = listOfObjects.filter { ... }
if (newSmth.isNotEmpty()) {
otherWorkflow.process(newSmth)
}
Eugen Martynov
07/15/2020, 6:46 PMclass DebounceClickListener(val clickListener:View.OnClickListener): View.OnClickListener{}
Afzal Najam
08/13/2020, 3:56 AMEugen Martynov
08/24/2020, 9:45 AMfilterNot
or filter { not condition }
. I missed Not
in the filterNot
recently in review. It is probably matter of time when I will be fine.Mark
08/30/2020, 2:33 AMclass FlowDelegate<T>: ReadWriteProperty<Any, Flow<T>> {
private val deferredFlow = CompletableDeferred<Flow<T>>()
override fun setValue(thisRef: Any, property: KProperty<*>, value: Flow<T>) {
deferredFlow.complete(value)
}
override fun getValue(thisRef: Any, property: KProperty<*>): Flow<T> {
return if (deferredFlow.isCompleted) {
deferredFlow.getCompleted()
} else {
flow {
emitAll(deferredFlow.await())
}
}
}
}
/** Usage */
class MySample {
private var _sampleFlow by FlowDelegate<String>()
val sampleFlow: Flow<String>
get() = _sampleFlow
fun init(args: ...) {
_sampleFlow = flow<String> { /* based on args */ }
}
}
KV
09/21/2020, 4:56 AMfun String?.trimTrailingZeros(): String? {
if (isNullOrEmpty() || this!!.indexOf(".") < 0) return this
return replace("0*$".toRegex(), "").replace("\\.$".toRegex(), "")
}
delblanco
10/21/2020, 10:37 AMlistOf(A,B,C)
I would like to end up with the following pairs: A to B, A to C, B to C
Currently I got something like this but it feels non-idiomatic and inefficient...
val users = listOf(User("A"), User("B"), User("C"))
val chats = users.flatMap{ u1 ->
users.filterNot { u1 == it }
.map { u2 -> Chat(setOf(u1, u2)) }
}.toSet() // filters out duplicates
christophsturm
10/24/2020, 11:10 AMdata class User(
val name: String,
val birthday: LocalDate
)
Find<User>().where(User::name.like("blah%").and(User::birthday.between(date1, date2)))
can i somehow change it to make it possible to remove the User::
part and rewrite it like
Find<User>().where(::name.like("blah%").and(::birthday.between(date1, date2)))e
Mark
11/03/2020, 1:38 AMSequence
of `String`s and apply lots of mapping operations. Now, after these mappings I want to access the original index in the sequence. However, if I use mapIndexedValue
then I need to change each mapping operation implementation. Instead, is it recommended to declare and use something like this (not tested) so that we can continue to use the same transforms as before? Side note: is there a danger in using mutable values like this?
data class IndexedMutableValue<T>(val index: Int, var value: T)
fun <T> Sequence<T>.withIndexedMutableValue(): Sequence<IndexedMutableValue<T>> =
mapIndexed { index, t ->
IndexedMutableValue(index, t)
}
fun <T> Sequence<IndexedMutableValue<T>>.mapIndexedMutable(transform: (T) -> T): Sequence<IndexedMutableValue<T>> {
forEach { it.value = transform(it.value) }
return this
}
fun <T> Sequence<IndexedMutableValue<T>>.mapIndexedMutableNotNull(transform: (T) -> T?): Sequence<IndexedMutableValue<T>> {
forEach { it.value = transform(it.value) ?: return@forEach }
return this
}
fun <T> Sequence<IndexedMutableValue<T>>.flatMapIndexedMutable(transform: (T) -> Sequence<T>): Sequence<IndexedMutableValue<T>> {
return sequence {
forEach { indexedValue ->
transform(indexedValue.value).forEach { newValue ->
yield(indexedValue.copy(value = newValue))
}
}
}
}
jean
11/13/2020, 7:44 AMprivate fun cookieStringToMap(string: String): Map<String, String> {
val map = mutableMapOf<String, String>()
string.split(";").forEach { entry ->
val parts = entry.split("=")
map[parts[0]] = parts[1]
}
return map
}
christophsturm
11/24/2020, 3:35 PMreturn if (value != null)
(value as Number).toDouble()
else
null
(not (value as? Number).toDouble()
, which acts differently)LastExceed
12/16/2020, 12:49 PMJoris PZ
12/20/2020, 7:57 AMenum class OpCode(val code: Int) {
QUERY(0), IQUERY(1), STATUS(2), NOTIFY(4), UPDATE(5), UNSUPPORTED(-1);
}
fun Int.toOpCode(): OpCode {
return OpCode.values().find { it.code == this } ?: OpCode.UNSUPPORTED.also {
log.error { "Unsupported DNS OpCode $this" }
}
}
This uses a receiver function, which I like in general, and obviously there are many different ways of writing this function (such as fun toOpcode(code:Int): Opcode
) etc.
Now, it occurred to me that this is also possible:
enum class OpCode(val code: Int) {
QUERY(0), IQUERY(1), STATUS(2), NOTIFY(4), UPDATE(5), UNSUPPORTED(-1);
companion object {
operator fun invoke(code: Int): OpCode {
return values().find { it.code == code } ?: UNSUPPORTED.also {
log.error { "Unsupported DNS OpCode $this" }
}
}
}
}
This allows the caller to map an Int
to an OpCode
using what looks like a constructor: val code = OpCode(0)
What would you say if you saw this in a pull request? Is this clever and nice, or horrible and confusing and just showing off? I keep switching sides myself... 🙂Mark
12/30/2020, 12:11 PMinline fun <reified K, V> Map<out K?, V>.filterKeyNotNull(): Map<K, V> =
mapNotNull { (key, value) -> if (key != null) key to value else null }.toMap()
jean
01/07/2021, 8:31 AMlifecycleScope.launch {
viewModel.state.collect { updateState(it, binding) }
}
lifecycleScope.launch {
viewModel.load()
}
I cannot have viewModel.load()
inside the first block after collect
since it never ends and if I put it before I miss a bunch of events. Is there a way to write this in a better way?Milan Hruban
01/07/2021, 11:31 AM<http://logger.info|logger.info>("the value is $value")
2️⃣ passing additional arguments - <http://logger.info|logger.info>("the value is {}", value)
3️⃣ :thread-please: something else?alex cole
01/10/2021, 1:36 AMtoNumber()
for the following code to follow the kotlin style guide.
class ArrayND {
var data: ArrayList<Double> = {...}
var shape: Array<Int> = {...}
operator fun get(vararg indicies: Int): ArrayND {...}
fun toNumber(): Double {
if (data.size == 1) {
return data[0]
} else {
Throw Error
}
}
}
Paulo Pinheiro
01/13/2021, 11:34 AMPaulo Pinheiro
01/13/2021, 11:34 AMPaul Woitaschek
01/15/2021, 3:05 PMPaulo Pinheiro
01/18/2021, 9:46 AM