Jitendra
07/20/2022, 10:56 AMLucas
07/20/2022, 1:48 PMJasmin Fajkic
07/20/2022, 7:20 PMfunction extractTime(time) {
return {
seconds: moment().diff(time, 'seconds'),
minutes: moment().diff(time, 'minutes'),
hours: moment().diff(time, 'hours'),
days: moment().diff(time, 'days'),
weeks: moment().diff(time, 'weeks'),
months: moment().diff(time, 'months'),
years: moment().diff(time, 'years'),
};
}
Is there something similar in Kotlin that I can achieve same result?Lukasz Kalnik
07/22/2022, 11:53 AMif ... else
expression?
val myLambda: () -> Unit = if (condition) doSomethingLambda else {{}}
nkiesel
07/23/2022, 1:22 AMval tree = mapOf(2 to 1, 3 to 2, 4 to 3, 5 to 1)
fun allPath(tree: Map<Int, Int>, root: Int): Map<Int, List<Int>> {
return (tree.keys.associateWith { path(it, tree, root) } + mapOf(root to listOf(root))).filterValues { it.isNotEmpty() }
}
fun path(start: Int, tree: Map<Int, Int>, root: Int): List<Int> {
return buildList {
var n: Int? = start
while (n != null && n != root) { add(n); n = tree[n] }
if (n == null) return emptyList()
add(root)
}.reversed()
}
println(allPath(tree, 1)) // prints {2=[1, 2], 3=[1, 2, 3], 4=[1, 2, 3, 4], 5=[1, 5], 1=[1]}
Colton Idle
07/23/2022, 4:02 AMsealed interface UserType {
object GUEST : UserType
class AUTHENTICATED(
val authToken: String,
) : UserType
}
zero_coding
07/23/2022, 7:40 AMColton Idle
07/24/2022, 9:38 PMfun updateUser(username: String? = null, email: String? = null, token: String? = null) {
if (username != null) {
_appUser.value = _appUser.value?.copy(username = username)
}
if (email != null) {
_appUser.value = _appUser.value?.copy(email = email)
}
if (token != null) {
_appUser.value = _appUser.value?.copy(authToken = token)
}
}
Vitali Plagov
07/25/2022, 7:51 AMopen class Parent {
fun load() {
return ... // don't know what to return here
}
}
class ChildA : Parent () {
fun methodA() = ...
}
class ChildB : Parent () {
fun methodB() = ...
}
class Usage {
fun fooA() {
ChildA().load().methodA() // I want to achieve this chaining
}
fun fooA() {
ChildB().load().methodB()
}
}
martmists
07/25/2022, 10:54 AMsomeFunction( // takes varargs
*arrayOf(if (condition) "someValue" else null).filterNotNull().toTypedArray(),
)
Vampire
07/25/2022, 11:43 AMimport org.gradle.api.Action
inline fun <T> action(crossinline block: T.() -> Unit): Action<T> {
return object : Action<T> {
override fun execute(t: T) {
t.run(block)
}
}
}
But updating Gradle to 7.5 and thus Kotlin to 1.6.10 now gives a compilation error (well warning, but we have -Werror
) about wrong nullability:
w: ...\buildSrc\src\main\kotlin\...\util\SamHelper.kt: (10, 7): Override 'fun execute(t: T): Unit' has incorrect nullability in its signature comparing with overridden 'fun execute(p0: T): Unit'
What is his problem suddenly and how do I mitigate it?zain
07/26/2022, 11:49 AMdata class Stat(
val bR: Int? = 1,
val cS: Int? = 2,
val fP: Int? = 3,
val gA: Int? = 4,
val gC: Int? = 5,
val gOB: Int? = 6,
val gS: Int? = 7
)
How do I get all properties and their respective values of an object?
val stat = Stat( )
stat.forEach { property, value
}
Is this possible in Kotlin?Dmitry Romanov [JB]
07/26/2022, 2:08 PMGavin Ray
07/26/2022, 6:10 PMList
version but you never know, figured I'd ask others:
fun recur(...): Sequence<*> = sequence {
yield(...)
getQueryRelations(innerRequest).forEach {
yieldAll(
recur(...)
)
}
}
fun recur(...): List<*> {
return listOf(...) + getQueryRelations(innerRequest).flatMap {
recur(...)
}
}
Jason5lee
07/27/2022, 7:43 AMclass Scope {
fun method(block: () -> Unit) {}
}
fun scope(block: Scope.() -> Unit) {}
fun main() {
scope {
method {
method { } // I want to disallow using the scope inside the method
}
}
}
I want to disallow calling method on the Scope
inside the method
.
I know I can have a dummy receive object and mark the Scope
and the dummy object DslMarker
.
@DslMarker
annotation class MyDslMarker
@MyDslMarker
class Scope {
fun method(block: Context.() -> Unit) {}
}
@MyDslMarker
object Context // Dummy object
fun scope(block: Scope.() -> Unit) {}
fun main() {
scope {
method {
method { } // Compiler error now
}
}
}
Any better solution?Nat Strangerweather
07/27/2022, 12:16 PMval skillRating = MutableLiveData(0)
fun calculateSkillRating() {
if (readWinCount.value != 0 && readLossCount.value != 0) {
skillRating.value = averageWinningScore.value?.plus(
(400 * (readWinCount.value?.minus(readLossCount.value!!)!!) /
(readWinCount.value?.plus(readLossCount.value!!)!!))
)
}
}
janvladimirmostert
07/27/2022, 9:08 PMval a = fun (): String {
return ""
}
or
val a = fun () = ""
and lambda expression
val b: () -> String = {
""
}
or
val b = { "" }
in any way other than just the syntax?phldavies
07/28/2022, 10:59 PMfun CtxA.action() = CtxA
fun CtxC.action() = Unit
context(CtxA, CtxB)
fun bothContexts() {
// Overload resolution ambiguity. All these functions match.
// public fun CtxA.action(): CtxA defined in root package in file CtxRcv.kt
// public fun CtxC.action(): Unit defined in root package in file CtxRcv.kt
action()
}
context(CtxA)
fun onlyCtxA() = action() // works fine
As far as I can tell, it shouldn’t even be considering CtxC.action
as a candidate as it’s not in scope. I can qualify as this@CtxA.action()
but obviously not ideal.sen
07/29/2022, 3:13 AMfun SomeClass.someFunction(param: Int) {
// Do something...
}
We would invoke it as
SomeClass().someFunction(5)
and in Java it would be
KotlinClassKt.someFunction( /** this$SomeClass **/ SomeClass(), 5)
So my question is, can I change the parameter of the function?Ayfri
07/29/2022, 12:33 PMMatt Yokan
07/30/2022, 12:23 AMGavin Ray
07/30/2022, 5:30 PMquasiquotes
, which let you quote Scala code to have it be evaluated as an AST + compiled instead of interpreted
This makes codegen really easy compared to using something like Janino
Does Kotlin have something similar? Maybe in the K2 internal API's or something?
I didn't find anything on Google searching for kotlin codegen library
=/Gavin Ray
07/30/2022, 5:34 PMdef eval(e: Expression): AST = e match {
case Literal(value) => q"$value"
case Attribute(name) => q"row.get($name)"
case Add(left, right) => q"${eval(left)} + ${eval(right)}"
}
juh juh
07/31/2022, 8:27 PMEric Boggs
07/31/2022, 10:36 PMGleb Minaev
08/01/2022, 4:13 PMjvm-abi-gen
compiler plugin that was mentioned in 1.7.20-Beta release notes? I can not find any documentation on it.juh juh
08/01/2022, 8:26 PMnull
val tempLines = Array<IntArray?>(width + height) { null } as Array<IntArray>
for (x in 0 until width) {
tempLines[x] = IntArray(height) { y -> x + y * width }
}
for (y in 0 until height) {
tempLines[y + width] = IntArray(width) { x -> x + y * width }
}
Creating two arrays and concatenating them via +
is not an option, because performance is very criticalsundernegi
08/02/2022, 11:37 AMNat Strangerweather
07/14/2022, 1:12 PMfun getWordValue() {
val workingArray = repository.arr.distinct()
val list = mutableListOf(0)
word.value!!.forEach { c ->
workingArray.forEach {
if (it.name.contains(c)) {
when (c) {
word.value!![0] -> list.add(it.value)
word.value!![1] -> list.add(it.value)
word.value!![2] -> list.add(it.value)
else -> list.add((it.value * 2))
}
}
}
}
wordValue.value = list.sum()
saveWordValue(wordValue.value!!)
}
I'd be grateful for some help, thanks!Nat Strangerweather
07/14/2022, 1:12 PMfun getWordValue() {
val workingArray = repository.arr.distinct()
val list = mutableListOf(0)
word.value!!.forEach { c ->
workingArray.forEach {
if (it.name.contains(c)) {
when (c) {
word.value!![0] -> list.add(it.value)
word.value!![1] -> list.add(it.value)
word.value!![2] -> list.add(it.value)
else -> list.add((it.value * 2))
}
}
}
}
wordValue.value = list.sum()
saveWordValue(wordValue.value!!)
}
I'd be grateful for some help, thanks!Sam
07/14/2022, 1:16 PMrepository
, word
and wordValue
are.Joffrey
07/14/2022, 1:16 PMSam
07/14/2022, 1:17 PMNat Strangerweather
07/14/2022, 1:18 PMdistinct
in my workingArray
is that some of the scrabble letters are repeated several times. Each letter has a name and a value.Sam
07/14/2022, 1:32 PMword.value!!.forEach { c ->
to
word.value!!.forEachIndexed { i, c ->
Where i
will give you the position of the character in the word.Giorgos Makris
07/14/2022, 1:48 PMJoffrey
07/14/2022, 1:51 PMGiven a character and its index in the word, can you find its value?Actually this would be easy if instead of converting the letters array by just using
distinct()
you used a Map<Char, Int>
from letter to value:
val lettersToValues = repository.arr.associate { it.name to it.value }
Nat Strangerweather
07/14/2022, 2:19 PMNolan
07/15/2022, 1:58 PMwhen
statement will always hit the first condition in the scenario you described because it's comparing the values. So if your word is "EXCEPT", the first "E" and the fourth "E" will match word.value!![0]
because that evaluates to "E".Nat Strangerweather
07/15/2022, 8:23 PMwhen
statement in order to make my code less awkward, and using the suggestions that were made above. But it's good to know why this did not work in the first place. 😊 Here is what the code looks like now:
fun getWordValue() {
val list = mutableListOf(0)
val lettersToValues = repository.arr.associate { it.name to it.value }
word.value!!.forEachIndexed() { i, c: Char ->
if (i in 0..2) {
list.add(lettersToValues.getValue(c.toString()))
} else {
list.add(lettersToValues.getValue(c.toString()) * 2)
}
}
wordValue.value = list.sum()
saveWordValue(wordValue.value!!)
}
Joffrey
07/15/2022, 9:21 PMGiorgos Makris
07/15/2022, 10:30 PMNat Strangerweather
08/02/2022, 1:28 PMfun getWordValue() {
val lettersToValues = repository.arr.associate { it.name to it.value }
word.value!!.forEachIndexed { i, c: Char ->
if (i in 0..2) {
lettersToValues.getValue(c.toString())
} else {
lettersToValues.getValue(c.toString()) * 2
}
wordValue.value = c.toString().sumOf { i }
}
}
Sam
08/02/2022, 1:32 PMlettersToValues.getValue(…)
but you don’t seem to do anything with the result. In an earlier version of your code you were adding it to a list, I think.c.toString().sumOf { i }
also looks odd, and probably doesn’t do what you want it to.Nat Strangerweather
08/02/2022, 1:33 PMSam
08/02/2022, 1:33 PMNat Strangerweather
08/02/2022, 1:33 PMJoffrey
08/02/2022, 6:14 PMfold
which is a functional way of doing it.