DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Why Kotlin Multiplatform is a Game-Changer for Startup Teams
  • Kotlin Code Style: Best Practices for Former Java Developers
  • Metal and the Simulated Annealing Algorithm
  • Reactive Kafka With Spring Boot

Trending

  • Why Your QA Engineer Should Be the Most Stubborn Person on the Team
  • How to Build and Optimize AI Models for Real-World Applications
  • Production Database Migration or Modernization: A Comprehensive Planning Guide [Part 2]
  • We Went Multi-Cloud and Almost Drowned: Lessons From Running Across AWS, GCP, and Azure
  1. DZone
  2. Coding
  3. Languages
  4. Learning Kotlin: Invoke

Learning Kotlin: Invoke

Want to learn more about type of operators in Kotlin? Check out this tutorial to learn more about using the Invoke method in Kotlin.

By 
Robert Maclean user avatar
Robert Maclean
·
Updated Sep. 25, 18 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
20.7K Views

Join the DZone community and get the full member experience.

Join For Free

Today, we tackle a weird operator, invoke, which lets an instance of a class have a default function that I am not sure I've ever seen any language do. So, let us explore this with a simple example. We have a config class that returns the configuration for something, like this:

class Config {
fun get():String {
// do stuff
return "stuff"
}
}

fun main(args: Array<String>) {
val config = Config()
println(config.get())
}


Now, in our world, maybe get is the primary use, so we can actually make it that the instance config (line 9) can be called to get it:

class Config {
operator fun invoke(): String {
return this.get();
}

private fun get():String {
// do stuff
return "stuff"
}
}

fun main(args: Array<String>) {
val config = Config()
println(config())
}


Note that we add a new operator (line 2), and that calls the private get. It didn't need to be private, but I thought this would be cleaner, and now on line 14, we can just call the instance itself.

Now, you may be thinking, "nice, but so what — saving a few keystrokes isn't too awesome." Well, invoke can return anything, including itself, which opens up something crazy!

class Config {
var count = 0;
operator fun invoke(): Config {
count++
return this
}
}

fun main(args: Array<String>) {
val config = Config()
config()()()()()()()()()()
println("config was called ${config.count} times")
}


This will print out config was called 10 times. That is a lot more interesting, so let us ramp up another level and pass parameters to invoke:

class Config {
var word = ""
operator fun invoke(s: String): Config {
word += s
return this
}
}

fun main(args: Array<String>) {
val config = Config()
config("R")("o")("b")("e")("r")("t")
println(config.word)
}


While I do not know yet where I would use this myself, I do use invoke all the time. Since it is what makes lambdas possible in Kotlin because when we create a lambda, we get an object that is invoked with, well, invoke.

Kotlin (programming language)

Published at DZone with permission of Robert Maclean. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why Kotlin Multiplatform is a Game-Changer for Startup Teams
  • Kotlin Code Style: Best Practices for Former Java Developers
  • Metal and the Simulated Annealing Algorithm
  • Reactive Kafka With Spring Boot

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook