Skip to Content

Abusing Kotlin's Unicode Support for Fun

Having fun with extension functions and unicode

Posted on

One fun feature of Kotlin is its ability to use most of the Unicode character set for function names if you enclose them in backticks. Enclosing function names in backticks is a common pattern for naming your tests senisbly , or for escaping keywords when interoperating with Java. That’s all well and good, but let’s abuse this feature for fun. And random numbers.

We’re going to define an extension function, to give us random numbers limited by the receiver.

// Extension function on Int
fun Int.`¯\_(ツ)_/¯`(source: Random = Random()): Int = source.nextInt(this)

And to call it, we would do this:

// Random Int between 0-9
val randomInt = 10.`¯\_(ツ)_/¯`()  

// Random Int between 0-9, with the given Random as a source.
val randomInt = 10.`¯\_(ツ)_/¯`(myRandom) 

Is that useful? No. It’s hard to type, IntelliJ won’t auto-suggest it, and I’m positive your co-workers will hate it. But that shouldn’t stop you from having fun with it!

In order to define Shruggy up there, I could’t use the standard backslash (\) or foreslash (/) that represent its arms, because Kotlin doesn’t like that. Instead, I found similar characters that look close that Kotlin will allow, the Fullwidth Solidus and the Fullwidth Reverse Solidus .

For the sake of completeness, I leave you with this, the full set of shruggy-random extensions:

fun Int.`¯\_(ツ)_/¯`(source: Random = Random()): Int = source.nextInt(this)
fun Long.`¯\_(ツ)_/¯`(source: Random = Random()): Long = (source.nextDouble() * this).toLong()
fun Float.`¯\_(ツ)_/¯`(source: Random = Random()): Float = source.nextFloat() * this
fun Double.`¯\_(ツ)_/¯`(source: Random = Random()): Double = source.nextDouble() * this

And of course, you could define this as a function for a coin toss:

fun `¯\_(ツ)_/¯`(source: Random = Random()): Boolean = source.nextBoolean()

I take none of the blame for what your co-workers think of you if you use this. I wonder if there’s an open source license that explicitly disclaims things like that?

If you do use this in a project and live to tell the tale, I’d love to hear from you!