Skip to content

Instantly share code, notes, and snippets.

@JanMalch
Created August 4, 2020 17:11
Show Gist options
  • Save JanMalch/5fd64d5ee3a7d523ed682dbd161fc027 to your computer and use it in GitHub Desktop.
Save JanMalch/5fd64d5ee3a7d523ed682dbd161fc027 to your computer and use it in GitHub Desktop.
Small demo of combining custom operators and function literals with receivers.
class CaesarConverter {
// cannot use operator plus because it would be shadowed and not used
operator fun String.minus(offset: Int) =
this.toCharArray().map { it - offset }.joinToString(separator = "") { it.toString() }
}
fun caesar(block: CaesarConverter.() -> String) = CaesarConverter().block()
fun main() {
val encrypted = caesar { "test" - 4 }
val decrypted = caesar { encrypted - -4 }
println("test -> $encrypted -> $decrypted")
// test -> paop -> test
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment