简体   繁体   中英

default value for arguments of lambda function in Kotlin

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?

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 (ie 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 (ie 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 ), ie:

{ 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM