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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Window Closes: Why I Switched to Kotlin Before the Codebase Got Too Big
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • Parallel Kafka Batch Processing With Kotlin Coroutines in Spring Boot

Trending

  • Stop Writing Database Migration Scripts: Declarative Schema Sync for Java
  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Build a Voice Assistant With Gemini Live API

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Updated Sep. 25, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
20.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • The Window Closes: Why I Switched to Kotlin Before the Codebase Got Too Big
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Why Kotlin or Java Is the Wrong Question For Enterprises
  • Parallel Kafka Batch Processing With Kotlin Coroutines in Spring Boot

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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