Screenshot 2018-11-06 at 8.14.57 PM.png
# announcements
v
Screenshot 2018-11-06 at 8.14.57 PM.png
v
I expect you want something like
initialValue: T?
v
I want the caller to decide the nullability of T
So
ObservableField("").get()
returns non-null type, but
ObservableField(null).get()
returns nullable type
This is what I want to achieve, is it possible?
d
That should be possible. This example behaves as expected:
Copy code
fun main() {
    val d1 = Demo<String>("asdf")
    val d2 = Demo<String?>(null)
    
    onlyAcceptsNonNullableStrings(d1.getItem())
    // onlyAcceptsNonNullableStrings(d2.getItem()) // This is a compiler error
}

fun onlyAcceptsNonNullableStrings(value: String) {
    //do whatever
}

class Demo<T>(private val item: T) {
    fun getItem(): T {
    	return item
    }
}
Maybe remove the upper bound from your class definition?
s
no, I don’t think this can work with that secondary constructor
like if you call
ObservableField<String>()
, how does that work?
you can’t call
this(null)
if
T
is
String
d
Right, in that case with the secondary constructor that won’t be possible because
Any
is kind of a subclass of
Any?
so that’s not always going to be a legal call, because T could be non-nullable.
https://www.kotlindevelopment.com/typical-kotlin/ has some useful information about how nullable types work
d
I believe the code shown initially will work with experimental (new) type inference in kotlin 1.3.
v
ooh, I’ll try it out, thanks!
d
@Dico I don’t think it’s going to work in NI, because it has nothing to do with inference to begin with (all types are explicitly written down here). This is an ordinary type-checking, and it should fail because of reasons already mentioned above.
d
Oh, I'm an idiot. Excuse me 😀
d
Totally no problem, we all humans here 👌
i
A similar idea was discussed in the forum before: https://discuss.kotlinlang.org/t/nulls-and-generics/2219 Perhaps it's time to create a feature request out of that.
v
thanks for the link!