elect
05/29/2020, 8:35 AMAny
to overwrite a default toBoolean()
.
This would by default evaluate true
, for not nullable objects. (https://www.concurnas.com/docs/controlStatements.html#toboolean)
class MyCounter(var cnt: Int = 0) {
override toBoolean() = cnt > 0
}
var counter: MyCounter? = null
if(counter) // -> false
...
counter = MyCounter()
if(counter) -> false
..
counter.cnt++
if(counter) -> true
..
elizarov
05/29/2020, 8:59 AMelect
05/29/2020, 9:02 AMCody Engel
05/29/2020, 1:59 PMelect
05/29/2020, 2:00 PMelect
05/29/2020, 2:00 PMCody Engel
05/29/2020, 2:10 PMelect
05/29/2020, 2:22 PMCody Engel
05/29/2020, 2:48 PMtoBoolean
on Any
could have unintended consequences. One example I can think is third party libraries, if they overwrite the functionality would it cascade into my app? If two overwrite the functionality which one would win out?
I may be misunderstanding this as well, but that case in particular has me a little concerned.elect
05/29/2020, 4:05 PMelect
05/29/2020, 4:06 PMDerek Peirce
05/29/2020, 5:09 PM.check()
extension method to each of the relevant classes? That way, you won't ever actually count on a toBoolean()
call on an object that's actually using the default non-null check instead of the check you want.
The behavior you're asking for exists in Python, but it's problematic. You may think you're checking if an arbitrary object is null, but wait, it's a list, so you're actually checking if it's empty as well! Having specific .check()
methods may avoid this, the relevant method would always be known at compile-time instead of runtime.elect
05/29/2020, 5:12 PMCody Engel
05/29/2020, 5:50 PMshouldn't use it for nullable listsGoes against Kotlin's design philosophy IMO. My counter argument will always be "if I am allowed to do something, I will do it" so if I'm allowed to do something but I really shouldn't the system should be designed in such a way that I just can't do it.
elect
05/29/2020, 5:51 PMelect
05/29/2020, 5:51 PMelect
05/29/2020, 5:53 PM