Reputation: 1902
I have such enum with lambda in constructor
enum class EventType(
val getInfoBlocks: (Book, AuditEntity?) -> List<InfoBlock>? = { _, _ -> emptyList() }
) {...}
Now I use this lambda function like this:
data = it.getInfoBlocks.invoke(deal, null)
Can I do without null? Is there a way to set the default value for null lambda function arguments?
Upvotes: 6
Views: 2945
Reputation: 14917
TL;DR: function types cannot have default parameter values associated with them.
This is something only named (non-anonymous) functions can do.
However, there is likely a better solution for your problem.
No, anonymous functions (i.e. lambda expressions and fun
blocks) are not allowed to specify default values for their parameters.
However, what you propose is even more involved than this: you seem to want the default value to be associated with the function's type, so it would remain the same, regardless of which function is assigned to this property.
Because this default value would depend on the type of the variable that the function has been assigned to, for this to be possible, the type system would need a way to store the default argument value in the function's type information (i.e. something like (Book, AuditEntity? = null) -> List<InfoBlock>?
), and there's no way to do this.
However, given that this is an enum, there's no need to store an anonymous function as a property; simply declare a virtual function and override it as necessary:
enum class EventType {
// Type1 has the default implementation
Type1,
// Type2 has its own implementation
Type2 {
override fun getInfoBlocks(book: Book, entity: AuditEntity?): List<InfoBlock>? {
// Do something else
return foo()
}
};
// Default implementation
open fun getInfoBlocks(book: Book, entity: AuditEntity? = null): List<InfoBlock>? {
return emptyList()
}
}
(note that the semicolon is required to terminate the list of constants.)
This is similar to (but not the same as) why it's impossible to specify a default argument within an anonymous function itself (see also this question), i.e.:
{ a: Any, b: Any? = null -> foo() }
As not even this is possible, it makes sense that there wouldn't be a way to specify a default argument for an entire family of functions.
Upvotes: 5
Reputation: 81929
Yeah, do not use a lambda but make it an ordinary function :)
fun getInfoBlocks (x: Book, y: AuditEntity? = null) : List<InfoBlock> = emptyList()
Upvotes: 2