How to make a generic parameter "optional/default"...
# getting-started
d
How to make a generic parameter "optional/default" when it's needed just in an optional function parameter?
Copy code
fun <T> foo(arg: String, handler: (String) -> T = {}): T
I would like to define the function so that it's possible to call it with a default parameter:
Copy code
foo("abc")
Ideally I would like to avoid specifying the type param in this case, but even calling
foo<Unit>("abc")
would be fine.
The trouble is that I don't know how to make the default parameter. Currently it doesn't compile with:
Copy code
[TYPE_MISMATCH] Type mismatch.
Required:
T
Found:
Unit
(Of course, the real-life function is more complex so e.g. simply using overloading isn't a good option.)
j
It's not possible to have a default value for a generic type parameter, so there is no such thing as a "default `T`" for you. Now, your second parameter is a function that's supposed to return
T
. If you want to provide a default value for that one, it has to match any possible
T
that someone would use on the call site, which is generally not possible either, unless your default lambda just throws and returns
Nothing
🙂
The best option for you is to define a non-generic overload:
Copy code
fun foo(arg: String): Unit = foo<Unit>(arg) {}

fun <T> foo(arg: String, handler: (String) -> T): T {
    ...
}
Of course, the real-life function is more complex so e.g. simply using overloading isn't a good option
Then please show the real-life function 😉
d
Ah, I for some reason thought that the overload must be complicated than that 😄
It's just somewhat visually/syntactically disappointing seeing
Copy code
fun foo(arg: String): Unit = foo(arg) {}
and not being able to convert this to a default parameter 🙂
j
Yeah, I know, but when you think about why, it kinda makes sense. So I made my peace with it :)
d
Sure, it totally makes sense.
t
You can also make the block nullable:
Copy code
fun <T> foo(arg: String, handler: ((String) -> T)? = null): T
But I guess that won't help you to return T from that function...
172 Views