Probably this is a super FAQ, but if another modul...
# stdlib
d
Probably this is a super FAQ, but if another module in my project has
data class Value(val foo: Foo?)
and I do
if (value.foo != null) foo.bar() else doStuff()
, there's an error "smart cast is impossible". But if I know that a) it's val b) no multithreading is used, can I "smarten" the compiler? Perhaps by adding some
contract
somewhere? Is there a YouTrack issue along these lines maybe?
d
Compiler assumes that such smartcast is unstable because of ability of using different library versions in compile time and runtime Assume you compiled your code against
data class Value(val foo: Foo?)
, and then, sometimes in future on server you updated that library to newer version, which also includes change
foo
from
val
to
var
.
today i learned 3
d
On one hand I can see why this is reasonable, but on the other, this is the code sitting right in the next module of my app, I have full control of it and I'm 99% sure it will stay this way for the foreseeable future. I wish there was a way to tell the comiler that I'm really sure it's safe here.
d
Unfortunately, there is no difference for compiler between neighbor module or third-party lib
👌 1
e
this should be legal with
value class
t
@ephemient There's also possibility of changing val to val with non-pure getter. For example:
Copy code
// data class A (val a : String)

data class A private constructor (val b : Int) {
    val a : String
    	get() = rendomChar().repeat(b)
    
    constructor (a : String) : this(a.length)
}
But I would love an annotation that complier would understand that would imply public contract that a getter or a method is pure and it's result won't be affected by any change of object's or global state.
e
value class
cannot be changed in such a way without breaking binary and source compatibility
t
@ephemient I don't know about binary compatibility, but my example maintains source compatibility in external API. (correct me if I'm wrong)
e
in data classes it is but in value classes it is not.
t
@ephemient Ah, sorry. Haven't noticed you're talking about
value classes
and not
data classes
. So I agree about binary compatibility. About source compatibility - wouldn't this dirty trick do - https://pl.kotl.in/KVcsMPy28 ?