How to create a single parameter function that can...
# announcements
r
How to create a single parameter function that can take both
String
or
String?
as a parameter and returns simple
String
when called with
String
or nullable
String?
when called with
String?
?
d
Copy code
fun <T : String?> foo(param: T): T = param
👍 2
r
Is it possible to return T without unchecked cast ?
d
Sure, depends on what you are doing.
r
Copy code
fun <T : String?> foo(str: T): T = str.toString()
this doesn't compile without additional cast
d
Well, yes, because
toString
always returns
String
, never
String?
What's your use-case here? Why do you require a return-type of
T
, not just
String
?
r
Just playing with the language ;-)
d
In your example it makes more sense to specify a return-type of
String
, which is assignable to
String?
anyways
r
Probably yes, but it requires additional
?.let
if I want to run it with nullable value
d
I am not sure I follow your argument
r
I'm just trying to move this check into the function
d
Can you show the actual code you want to replace?
r
Copy code
fun <T : String?> clean(str: T): T = str?.let {
    Source(it).renderer.toString()
} as T
I asked my question to find out if I can do it without this
as T
casting
IntelliJ complains about it with a warning
d
You can write two methods:
Copy code
fun clean(str: String): String = str.toString()
@JvmName("cleanNullable")
fun clean(str: String?): String? = str?.let { clean(it) }
Or, more kotlin-like, make
clean
an extension function and move the null-check outside:
Copy code
fun String.clean() = this.toString()

// called as:
val foo: String? = TODO()
val cleaned = foo?.clean()
Personally I'd prefer the latter approach
r
Thx
Good idea