Rewrite in kotlin and use a helper function.

Addresses: https://github.com/Stebalien/kotlin/commit/23e88f387f4ab1353c9ffe13c2995b144ee0b6ed#commitcomment-6084551