mirror of
https://github.com/apple/pkl.git
synced 2026-01-11 14:20:35 +01:00
[PR #1053] [MERGED] Add getOrDefault method to Listing and Mapping
#867
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/apple/pkl/pull/1053
Author: @HT154
Created: 4/26/2025
Status: ✅ Merged
Merged: 7/23/2025
Merged by: @bioball
Base:
main← Head:getordefault📝 Commits (3)
d845b3bAdd getOrDefault method to Listing and Mappingf55a6ffaddress review feedback4c3d26eApply suggestions from code review📊 Changes
7 files changed (+65 additions, -2 deletions)
View changed files
📝
pkl-core/src/main/java/org/pkl/core/stdlib/base/ListingNodes.java(+16 -1)📝
pkl-core/src/main/java/org/pkl/core/stdlib/base/MappingNodes.java(+18 -1)📝
pkl-core/src/test/files/LanguageSnippetTests/input/listings/default.pkl(+4 -0)📝
pkl-core/src/test/files/LanguageSnippetTests/input/mappings/default.pkl(+4 -0)📝
pkl-core/src/test/files/LanguageSnippetTests/output/listings/default.pcf(+4 -0)📝
pkl-core/src/test/files/LanguageSnippetTests/output/mappings/default.pcf(+4 -0)📝
stdlib/base.pkl(+15 -0)📄 Description
This PR adds methods to
ListingandMappingthat can be used to retrieve members. If the member for the index/key isn't present, it appliesdefaultto the index/key. In both cases, this is essentially sugar forgetOrNull(<index/key>) ?? default.apply(<index/key>).I considered adding another method called something like
getOrElseto these types (as well asListandMap). This two-argument method would work likegetOrNullbut in the event of no member being present would return the second argument.I opted not to implement
getOrElsesince the null coalescing operator??already implements this in a more convenient way:getOrNull(<index/key>) ?? <default value>. I think the pattern of applyingdefaultshould have its own method: for many users it's not always obvious thatdefaultis a lambda, especially when it's defined via the sugared anonymous function object body syntax where the argument may be elided if unused.I'm definitely open to naming suggestions here!
I'm also unsure if
Dynamicwarrants a similar change. I'm currently of the mind thatDynamic.defaultshould be considered harmful due to #700.🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.