igor.wojda
01/13/2019, 7:50 PMprivate fun maxSubListSum(list: List<Int>, n: Int): Int? {
if (list.isEmpty()) {
return null
}
var max: Int? = null
(0..list.size - n).forEach { i ->
var temp: Int? = null
(i until (i + n)).forEach { j ->
if (temp == null) {
temp = list[j]
} else {
temp?.let { temp = it + list[j] }
}
}
temp?.let { localTemp ->
if(max == null) {
max = localTemp
} else {
max?.let { localMax ->
if(localTemp > localMax) {
max = temp
}
}
}
}
}
return max
}
However due temp
and max
being Int?
this temp
and max
assignments looks really creepy and requires bunch of let
. Is there easy way to simplify this 🤔🤔
temp?.let { localTemp ->
if(max == null) {
max = localTemp
} else {
max?.let { localMax ->
if(localTemp > localMax) {
max = temp
}
}
}
}
hudsonb
01/13/2019, 8:44 PMlet
are not needed, after if(temp == null)
, temp
will be smart cast to Int
Shawn
01/13/2019, 8:45 PMInt.MIN_VALUE
, right?Shawn
01/13/2019, 8:45 PMnull
requiredhudsonb
01/13/2019, 8:46 PMtemp
as in Int
in the else clause. And I'm with Shawn in eliminating the null
altogether would be better.hudsonb
01/13/2019, 8:52 PMforEach
. If you use a for
loop instead, smart cast will work.Shawn
01/13/2019, 8:53 PMforEach
in almost any case except, like, terminal Unit-returning operations on functional chainsDico
01/13/2019, 8:53 PM?.let {}
is preferable over if (x != null) {}
hudsonb
01/13/2019, 8:54 PMuser
09/10/2020, 12:00 PMuser
09/10/2020, 3:30 PMBrian Dilley
09/10/2020, 6:43 PMUnit
?Adam
09/11/2020, 4:56 AMuser
09/11/2020, 8:53 AMTwoClocks
09/12/2020, 3:40 AMHarry
09/13/2020, 11:31 AMShashank
09/13/2020, 1:54 PMStateFlow
by asserting the list of values received by it.
data class State(val isLoading: Boolean, val name: String?)
fun main() {
val mutableStateFlow = MutableStateFlow(State(false, null))
val stateFlow = mutableStateFlow as StateFlow<State>
val scope1 = CoroutineScope(Job())
val scope2 = CoroutineScope(Job())
scope1.launch {
delay(1000)
mutableStateFlow.value = State(true, null)
mutableStateFlow.value = State(false, "name")
}
scope2.launch {
stateFlow.collect {
println("value = $it")
}
}
Thread.sleep(2000)
}
Here is my code. Instead of getting State(true, null)
as the second value, I only receive the initial value and the last value (State(false, name)
)Jan Vomlel
09/14/2020, 8:30 AMSaul Wiggin
09/14/2020, 9:54 AMSaul Wiggin
09/14/2020, 9:54 AMephemient
09/14/2020, 10:02 AM@DeprecatedSinceKotlin("1.4")
(meaning it's not yet deprecated in 1.3)ephemient
09/14/2020, 10:03 AMuser
09/14/2020, 1:53 PMuser
09/14/2020, 1:54 PMuser
09/15/2020, 9:30 AMuser
09/15/2020, 4:00 PMSimon Lin
09/17/2020, 3:16 AMdata class Foo(val id: String? = null)
val list = listOf(Foo("0"), Foo(), Foo("2"))
// I would like to get ["0", "2"]
// I use this, but I don't like the Double !!
list.filter { it.id != null }
.map { it.id!! }
Shawn
09/17/2020, 3:26 AMlist.mapNotNull { it.id }
Rafal
09/17/2020, 5:53 AM