简体   繁体   中英

Kotlin lambdas and type inference

I implemented the following enum in Kotlin

enum class PlaylistAction(val playlistFilter:(Playlist) -> Boolean) {
    PLAY ({ it.playListOwner.Id == "xxx" }),
    SAVE({true})
}

I would like to use it to filter a List like this:

var test = playlists.filter { playlistActionType.playlistFilter}

where playlistActionType is of type PlaylistAction and playlists is List<Playlist>

But i am getting the following error:

Error:(122, 34) Type mismatch: inferred type is (Playlist) -> (Playlist) -> Boolean but (Playlist) -> Boolean was expected

Why is the inferred type (Playlist) -> (Playlist) -> Boolean and not (Playlist) -> Boolean?

By putting your predicate in {} , you are actually creating another lambda that returns your predicate as a result and this is why you end up with: (Playlist) -> (Playlist) -> Boolean instead of (Playlist) -> Boolean .

Using normal brackets should do the trick:

var test = playlists.filter(playlistActionType.playlistFilter)
var test = playlists.filter(playlistActionType.playlistFilter)

will work. You're passing a function to filter , there is no need for an additional lambda.

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