Kotlin’s :: operator and kewl things you can do with it

Kotlin’s :: operator and kewl things you can do with it
Photo by Connor Pope / Unsplash

Kotlin has many concise operators, but one of the “confusing” ones is the:: operator.

You’ve probably seen it a bunch of times in projects you’ve worked in. Java has it as well. The :: operator is called the callable reference operator. It gives you a reference to a function, property, or a constructor without invoking it. This has many applications, but in this post I’ll show you just a couple of popular applications.

You can see the carousel below for examples. So, we can use :: (callable reference operator) for…

  1. Passing functions as parameters. Then we can treat this reference as any other lambda. In our case, we will get a reference to the isEven() function. Getting a reference to a function is extremely useful for writing concise and clear code.
  2. Callbacks. Another popular use case of the :: operator is callbacks. Similar to our previous example, we can use this operator to reference a callback that we have defined elsewhere in our file.
  3. Reflection. Reflection is immensely handy in many use cases, such as dependency Injection, logging frameworks, and various libraries. The :: operator allows us to reference constructors, member variables, and other parts of our class. For example, you can do MyClass::class to access class metadata, or User::name to get a property reference. These are just a few ways you can use the ::operator in Kotlin — and I barely scratched the surface.

What’s your favorite use of the :: operator?

Subscribe to Multiplatform Mindset