https://kotlinlang.org logo
a

Antoine Gagnon

06/15/2020, 2:01 PM
Hey everyone, I’ve having some issues with type inference. I have a function similar to the one in SharedPreferences that retrieves a String, and if it doesn’t find it, it’ll return the default parameter that’s nullable
Copy code
fun getString(key: String?, default: String?): String?
The issue is that I’m trying to make it so that the compiler can tell if the default is null or not, and make the return type null or not. I’ve tried doing this:
Copy code
fun <T:String?>getString(key: String?, default: T): T
But if the default is value
null
, the inffered type becomes
Nothing?
instead of
String?
Any idea on how to do this properly?
l

Luis Mirabal

06/15/2020, 2:20 PM
One way could be to have a specific implementation for null and a different one for String:
fun getString(key: String?, default: Nothing?): String?
fun getString(key: String?, default: String): String
3 Views