See gh-25110

Comment From: snicoll

When merging this forward to 2.7.x we will need to add a Kotlin equivalent for this if possible.

Comment From: mhalbritter

Added the Kotlin code while merging 2.7.x. into main.