https://kotlinlang.org logo
#announcements
Title
# announcements
r

Robert Jaros

11/22/2019, 11:29 AM
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

diesieben07

11/22/2019, 11:30 AM
Copy code
fun <T : String?> foo(param: T): T = param
👍 2
r

Robert Jaros

11/22/2019, 11:32 AM
Is it possible to return T without unchecked cast ?
d

diesieben07

11/22/2019, 11:33 AM
Sure, depends on what you are doing.
r

Robert Jaros

11/22/2019, 11:33 AM
Copy code
fun <T : String?> foo(str: T): T = str.toString()
this doesn't compile without additional cast
d

diesieben07

11/22/2019, 11:33 AM
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

Robert Jaros

11/22/2019, 11:36 AM
Just playing with the language ;-)
d

diesieben07

11/22/2019, 11:37 AM
In your example it makes more sense to specify a return-type of
String
, which is assignable to
String?
anyways
r

Robert Jaros

11/22/2019, 11:39 AM
Probably yes, but it requires additional
?.let
if I want to run it with nullable value
d

diesieben07

11/22/2019, 11:39 AM
I am not sure I follow your argument
r

Robert Jaros

11/22/2019, 11:40 AM
I'm just trying to move this check into the function
d

diesieben07

11/22/2019, 11:40 AM
Can you show the actual code you want to replace?
r

Robert Jaros

11/22/2019, 11:42 AM
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

diesieben07

11/22/2019, 11:46 AM
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

Robert Jaros

11/22/2019, 11:49 AM
Thx
Good idea
2 Views