6

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?

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Yeah, do not use a lambda but make it an ordinary function :)

fun getInfoBlocks (x: Book, y: AuditEntity? = null) : List<InfoBlock>  = emptyList() 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.