dMusicb
11/28/2018, 9:20 PMdata class Testing(val test: Int = 5)
var test: Testing? = null
if (test == null) test = Testing(3)
test.test // works
test = test.copy() // works
for (i in (1..10)) {
test = test.copy() // complains about test being Testing?
}
diesieben07
11/28/2018, 9:28 PMtest
before the for-loop it invalidates any smart-casting information gathered before that point from then on, but fails to consider the actual type being assigned to test
.orangy
Alan Evans
11/28/2018, 9:32 PMdMusicb
11/28/2018, 9:34 PMdiesieben07
11/28/2018, 9:34 PMtest
inside the loopdiesieben07
11/28/2018, 9:35 PMval foo = test.copy()
in the loop, it works fine.dMusicb
11/28/2018, 9:36 PMAlan Evans
11/28/2018, 9:36 PMdMusicb
11/28/2018, 9:38 PMAlan Evans
11/28/2018, 9:39 PMvar test: Testing? = Testing(3)
test = test.copy() // not happy either
This case seems like something it could workout, but it's also like, why would anyone do this? Who would it help.
Your case is similar, why do you need nullability?diesieben07
11/28/2018, 9:39 PMAlan Evans
11/28/2018, 9:40 PMdata class Testing(val test: Int = 5)
var test: Testing = Testing(3)
test.test // works
test = test.copy() // works
for (i in (1..10)) {
test = test.copy() // works
}
Alan Evans
11/28/2018, 9:41 PMAlan Evans
11/28/2018, 9:42 PMdata class Testing(val test: Int = 5)
var test: Testing? = null
if (test == null) test = Testing(3)
test.test // works
var foo = test.copy() // works
for (i in (1..10)) {
foo = foo.copy() // works
}
test = foo
Alan Evans
11/28/2018, 9:45 PM!!
. I'd never recommend it.
!!
is a smell.dMusicb
11/28/2018, 9:51 PM...
val mapOfThings: Map<a, Thing?> = networkCallToGetThings()
for (a in b) { // b is List<a>
var thing = mapOfThings[a]
// do some logic with thing if it exists
if (thing == null) thing = Thing(...)
for (c in a.listOfC) {
// bunch of logic using thing, including updating some properties with
thing = thing.copy(...)
// use updated thing
}
}
...
diesieben07
11/28/2018, 9:52 PMmapOfThings.getOrPut(a) { Thing(...) }
?dMusicb
11/28/2018, 9:53 PMdMusicb
11/28/2018, 9:54 PMdMusicb
11/28/2018, 9:54 PMdMusicb
11/28/2018, 9:55 PMdiesieben07
11/28/2018, 9:57 PMval thing = mapOfThings[a]?.let { thing ->
// do stuff with thing if it exists
} ?: Thing(...)