Kotlin Lazy Initialization Example

Lazy Initialization is a common pattern for delaying creation of an object, calculation of a value, or an expensive process until it’s accessed for the first time. It is helpful when the initialization process consumes significant resources and the data isn’t always required when the object is used. Kotlin provides a good solution for that with lazy function. In this tutorial, we’re gonna look at a Kotlin Lazy Initialization example.

I. Technology

– Java 1.8
– Kotlin 1.1.2

II. Overview

Assume that we have a Person(name,books) class that lets us access a list of the books own by a person. Books list is stored in a database that we need time to access.

We want to load books on first access to the books property and do it only once.
It can be done with a delegated property:


data class Person(val name: String) {

	val books by lazy { loadBooks(this) }
}

lazy function (thread-safe by default) returns an object that has getValuemethod called.
– parameter of lazy is a lambda to initialize the value.

III. Practice

1. Helper Class

BookManager class handles processing data:


package com.javasampleapproach.lazyinit

class BookManager {

	companion object {

		fun loadBooks(person: Person): List {

			println("Load books for ${person.name}")
			return listOf("Master Kotlin at JavaSampleApproach", "Be Happy to become Kotlineer")
		}

	}
}

2. Class with delegated property


package com.javasampleapproach.lazyinit

data class Person(val name: String) {
	
	val books by lazy { BookManager.loadBooks(this) }
}

3. Run and check Result

Run the code below:


package com.javasampleapproach.lazyinit

fun main(args: Array) {
	
	val person = Person("Andrien")
	
	println(person.books)
	
	println("--- call again ---")
	println(person.books)
}

Check Result:


Load books for Andrien
[Master Kotlin at JavaSampleApproach, Be Happy to become Kotlineer]
--- call again ---
[Master Kotlin at JavaSampleApproach, Be Happy to become Kotlineer]

172 thoughts on “Kotlin Lazy Initialization Example”

  1. It’s perfect time to make a few plans for the future and it’s time
    to be happy. I have learn this publish and if I could I desire to
    suggest you few attention-grabbing issues or suggestions.
    Maybe you could write next articles referring to this article.
    I wish to read even more issues approximately it!

  2. I needed to thank you for this good read!! I definitely enjoyed every little bit of it.
    I have you bookmarked to look at new things you post…

  3. Hi there, just became aware of your blog through Google,
    and found that it’s truly informative. I’m going to watch out for brussels.
    I will appreciate if you continue this in future.
    A lot of people will be benefited from your writing.
    Cheers!

  4. I’m amazed, I have to admit. Seldom do I encounter a blog that’s both equally educative and engaging, and let me tell you, you
    have hit the nail on the head. The issue is an issue that too few folks are speaking intelligently
    about. I am very happy I found this during my hunt for something regarding this.

  5. you’re in point of fact a good webmaster. The site loading speed is incredible.

    It seems that you’re doing any unique trick. Moreover, The contents are masterpiece.
    you’ve done a magnificent job on this topic!

  6. What’s Going down i am new to this, I stumbled upon this I’ve discovered It absolutely helpful and it has helped me out loads.
    I am hoping to give a contribution & aid other customers like its helped
    me. Good job.

  7. I was recommended this blog through my cousin. I am now not certain whether or not this put up is written by
    him as no one else understand such detailed about my problem.
    You’re amazing! Thank you!

  8. Howdy just wanted to give you a quick heads up and
    let you know a few of the pictures aren’t loading properly.
    I’m not sure why but I think its a linking issue.
    I’ve tried it in two different internet browsers and both show the
    same results.

  9. I’m gone to convey my little brother, that he should also go to see this webpage on regular basis to
    get updated from most recent reports.

  10. Hey there! I just wish to give you a huge thumbs up for
    your excellent info you’ve got here on this post. I am returning to your web site for more soon.

  11. I have learn some excellent stuff here. Certainly value bookmarking for revisiting.
    I surprise how so much attempt you set to make the sort of fantastic
    informative website.

  12. Fantastic beat ! I wish to apprentice even as you amend your
    site, how could i subscribe for a blog web site? The account aided me a
    appropriate deal. I had been a little bit acquainted of this your
    broadcast provided bright transparent concept

  13. Howdy! I could have sworn I’ve visited this site before but after looking at many of the articles I realized
    it’s new to me. Anyhow, I’m certainly delighted I discovered it and I’ll be book-marking
    it and checking back regularly!

  14. I’ve been exploring for a little bit for any high-quality articles or weblog posts on this kind of
    house . Exploring in Yahoo I finally stumbled upon this site.
    Reading this info So i’m satisfied to exhibit that I have an incredibly excellent uncanny feeling I
    came upon just what I needed. I such a lot without a doubt
    will make certain to don?t fail to remember this site and provides it
    a glance on a continuing basis.

  15. Wow, superb blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look
    of your website is magnificent, as well as the content!

  16. Excellent blog you have here.. It’s hard to find quality
    writing like yours these days. I honestly appreciate individuals like you!

    Take care!!

  17. We’re a group of volunteers and starting a new
    scheme in our community. Your site provided us with valuable info to work on. You
    have done an impressive job and our whole community will be thankful to you.

  18. Aw, this was a really good post. Spending some time and actual effort to
    generate a really good article… but what can I say… I hesitate a
    lot and don’t manage to get nearly anything done.

  19. Just desire to say your article is as astonishing.
    The clearness on your publish is simply excellent and that i could suppose you are
    knowledgeable in this subject. Fine with your permission allow me to take hold of
    your RSS feed to stay updated with coming near near post.
    Thanks one million and please keep up the enjoyable work.

  20. Please let me know if you’re looking for a article writer
    for your site. You have some really good posts and I
    think I would be a good asset. If you ever want to take
    some of the load off, I’d love to write some content for your blog in exchange for a link back to mine.
    Please shoot me an email if interested. Kudos!

  21. I don’t even know how I stopped up here, but I thought this submit used to be
    great. I do not recognize who you’re however certainly you are going to a well-known blogger for those who aren’t already.
    Cheers!

  22. Hello, i think that i saw you visited my weblog thus
    i came to “return the favor”.I am trying to find things to improve my web site!I suppose its ok to use a few of your ideas!!

  23. Have you ever thought about writing an e-book or guest authoring on other websites?

    I have a blog centered on the same ideas you discuss
    and would really like to have you share some stories/information. I know my readers would enjoy your work.

    If you are even remotely interested, feel free to send
    me an email.

  24. Generally I do not learn post on blogs, but I wish to say that this write-up very forced
    me to take a look at and do it! Your writing style has been surprised me.
    Thanks, very great article.

  25. Thanks for every other informative website. The place else may I
    get that kind of information written in such a perfect manner?
    I’ve a challenge that I’m just now operating on, and I’ve been at the glance out
    for such information.

  26. Wonderful beat ! I would like to apprentice even as you amend your web site, how can i subscribe for
    a weblog web site? The account helped me a appropriate deal.
    I were a little bit acquainted of this your broadcast offered bright
    transparent concept

  27. Hello i am kavin, its my first occasion to commenting
    anyplace, when i read this paragraph i thought i could also make comment due to this brilliant article.

  28. What’s up, this weekend is good for me, because this occasion i am reading this fantastic educational piece of
    writing here at my house.

  29. Hi I am so glad I found your site, I really found you by error, while I was
    browsing on Google for something else, Regardless I am here
    now and would just like to say kudos for a remarkable post and a all
    round interesting blog (I also love the theme/design), I don’t have time to look
    over it all at the minute but I have book-marked
    it and also included your RSS feeds, so when I have time I will be back to read a great
    deal more, Please do keep up the superb jo.

  30. Simply desire to say your article is as amazing.
    The clearness in your post is simply cool and
    i can assume you’re an expert on this subject.
    Well with your permission let me to grab your feed to
    keep up to date with forthcoming post. Thanks a million and please continue the enjoyable work.

  31. Do you mind if I quote a few of your articles as long as I
    provide credit and sources back to your site? My blog site
    is in the exact same niche as yours and my visitors would definitely benefit from a lot of the information you present here.
    Please let me know if this ok with you. Many thanks!

  32. Amazing! This blog looks just like my old one!
    It’s on a completely different topic but
    it has pretty much the same page layout and design. Superb choice of colors!

  33. I’m gone to say to my little brother, that he should also visit this weblog on regular basis to take
    updated from most up-to-date information.

  34. Hello, this weekend is fastidious in support of me, for the reason that
    this moment i am reading this wonderful educational article here
    at my home.

  35. Magnificent goods from you, man. I have understand your
    stuff prior to and you’re just too great. I really like what you have got here, really like what
    you’re saying and the best way in which you assert it.

    You’re making it enjoyable and you continue to take care of
    to stay it sensible. I can’t wait to read far more from you.
    This is actually a wonderful web site.

  36. I loved as much as you will receive carried out right here.
    The sketch is tasteful, your authored material stylish. nonetheless, you
    command get got an edginess over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly
    the same nearly a lot often inside case you shield this increase.

  37. Asking questions are genuinely pleasant thing if you are not understanding something entirely, but this paragraph provides nice
    understanding even.

  38. Heya i am for the primary time here. I came across this board and I to find It really useful
    & it helped me out a lot. I hope to offer one
    thing again and aid others like you helped me.

  39. I’m amazed, I must say. Rarely do I encounter a blog that’s equally educative and engaging,
    and let me tell you, you have hit the nail on the head.
    The problem is an issue that not enough men and women are speaking intelligently about.
    Now i’m very happy that I came across this in my hunt for something relating to this.

  40. Heya i am for the first time here. I came across
    this board and I find It really helpful & it helped me out much.
    I am hoping to provide one thing again and aid others such as you helped me.

  41. Greetings! Very useful advice in this particular article!
    It is the little changes that will make the largest changes.
    Thanks for sharing!

  42. I am extremely impressed with your writing
    skills as well as with the layout on your blog. Is this a paid theme or did you customize it
    yourself? Either way keep up the excellent quality writing, it is rare to see a great blog like
    this one nowadays.

  43. What’s Taking place i’m new to this, I stumbled upon this I have discovered It absolutely useful and it has helped me out loads.
    I hope to contribute & help different users like its aided me.
    Great job.

  44. you’re in reality a excellent webmaster. The site loading velocity is amazing.
    It sort of feels that you are doing any unique trick. Moreover, The contents are masterwork.
    you’ve done a excellent process in this matter!

  45. Hello to every body, it’s my first go to see of this webpage;
    this weblog includes remarkable and genuinely excellent
    data in favor of visitors.

  46. Hey! I know this is somewhat off-topic however I needed to ask.

    Does managing a well-established website like yours
    take a lot of work? I am completely new to blogging however I
    do write in my diary on a daily basis. I’d like to start a blog so I will be able to share my
    own experience and thoughts online. Please let me
    know if you have any kind of ideas or tips for
    new aspiring bloggers. Thankyou!

  47. Thanks for a marvelous posting! I certainly enjoyed
    reading it, you could be a great author. I will ensure that I bookmark your blog and will come back in the future.
    I want to encourage you to definitely continue your great writing, have a nice afternoon!

  48. Hi! I know this is kind of off topic but I was wondering which blog platform are you
    using for this website? I’m getting fed up of WordPress because I’ve had issues with hackers and I’m looking at options for another platform.
    I would be great if you could point me in the direction of
    a good platform.

  49. Great blog here! Additionally your web site so much up very fast!
    What host are you the use of? Can I am getting your associate hyperlink to your host?

    I want my web site loaded up as fast as yours
    lol

  50. Thanks for your personal marvelous posting! I genuinely enjoyed
    reading it, you might be a great author.I will always bookmark your
    blog and definitely will come back very soon. I want to encourage yourself to continue your great writing,
    have a nice weekend!

  51. My family members always say that I am killing my time here
    at net, except I know I am getting familiarity every day by
    reading thes pleasant articles.

  52. Hi there, You’ve done a fantastic job. I’ll certainly
    digg it and personally suggest to my friends. I am confident
    they will be benefited from this web site.

  53. Unquestionably consider that that you stated. Your favourite reason appeared to be on the web the easiest thing to keep in mind of.
    I say to you, I definitely get irked even as other folks consider issues that they plainly don’t understand about.
    You controlled to hit the nail upon the highest as well as outlined out the whole thing without having side-effects , other folks
    can take a signal. Will likely be again to get more.
    Thanks

  54. First off I want to say fantastic blog! I had a quick question which I’d
    like to ask if you don’t mind. I was curious to know how you
    center yourself and clear your mind prior to writing. I have had difficulty clearing my
    thoughts in getting my thoughts out. I do enjoy writing
    but it just seems like the first 10 to 15 minutes
    are generally lost simply just trying to figure out how to begin. Any suggestions or hints?
    Kudos!

  55. Write more, thats all I have to say. Literally, it seems as
    though you relied on the video to make your point. You clearly know
    what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something informative to read?

  56. I’m not sure where you’re getting your information, but
    great topic. I needs to spend some time learning much more
    or understanding more. Thanks for magnificent info I was looking for this info for my mission.

  57. I like the helpful information you provide in your articles.
    I’ll bookmark your blog and check again here regularly.
    I’m quite certain I will learn many new stuff right here!
    Best of luck for the next!

  58. Wow that was unusual. I just wrote an incredibly long comment but after I
    clicked submit my comment didn’t appear. Grrrr…

    well I’m not writing all that over again. Regardless, just wanted to say wonderful blog!

  59. Hmm it appears like your website ate my first comment (it was extremely long) so I guess I’ll just sum it up
    what I had written and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog writer but I’m still new to the whole thing.
    Do you have any points for beginner blog writers?

    I’d certainly appreciate it.

  60. Hey there, You’ve done an excellent job. I’ll definitely digg it and personally recommend to my friends.
    I am confident they will be benefited from this web site.

  61. I was curious if you ever considered changing the page layout of your website?
    Its very well written; I love what youve
    got to say. But maybe you could a little more
    in the way of content so people could connect with it better.
    Youve got an awful lot of text for only having 1 or 2 pictures.
    Maybe you could space it out better?

  62. Aw, this was a really good post. Taking a
    few minutes and actual effort to make a really good article… but what can I say… I put things off a lot and don’t manage to get anything done.

  63. Hello there, I discovered your site by way of Google even as searching for a comparable matter, your web site came up, it
    seems great. I’ve bookmarked it in my google bookmarks.

    Hi there, simply turned into alert to your blog thru Google,
    and found that it’s really informative. I’m gonna be careful for brussels.
    I’ll be grateful for those who continue this in future.
    Lots of other folks will probably be benefited out of your writing.
    Cheers!

  64. Do you have a spam issue on this website; I also am a blogger, and I was wondering your situation; we have developed some nice procedures and we are looking to swap strategies with other folks, please shoot
    me an email if interested.

  65. Hi all, here every person is sharing these kinds of knowledge,
    so it’s nice to read this webpage, and I used to pay a
    quick visit this weblog every day.

  66. Definitely believe that which you said. Your favorite justification appeared to be on the web the simplest thing
    to be aware of. I say to you, I definitely get annoyed while people consider worries that they plainly do not know about.
    You managed to hit the nail upon the top and defined out the whole thing without having side effect , people could
    take a signal. Will probably be back to get more.
    Thanks

  67. Hello there, just became alert to your blog through Google, and
    found that it is truly informative. I’m going
    to watch out for brussels. I will appreciate if you continue this in future.
    Lots of people will be benefited from your writing.
    Cheers!

  68. What i don’t realize is actually how you’re no longer actually much more smartly-appreciated than you may be right now.
    You’re so intelligent. You recognize thus considerably relating to this subject, produced me individually consider it from numerous varied angles.

    Its like men and women are not interested except it is something to
    accomplish with Woman gaga! Your personal stuffs outstanding.
    At all times take care of it up!

  69. I just couldn’t leave your site before suggesting that I extremely enjoyed the usual information an individual provide on your visitors?

    Is going to be again steadily to inspect new posts

  70. Hi, i think that i saw you visited my weblog thus i came
    to return the want?.I am attempting to to find things to improve my web site!I guess its ok
    to use some of your concepts!!

  71. Hmm is anyone else encountering problems with the images on this blog loading?
    I’m trying to figure out if its a problem on my end or if it’s the blog.

    Any responses would be greatly appreciated.

  72. Hi there, You have done a great job. I will certainly digg
    it and personally recommend to my friends. I’m confident they will be benefited from this site.

  73. Whoa! This blog looks just like my old one! It’s on a
    totally different subject but it has pretty much the same layout and design. Superb choice of colors!

  74. You made some good points there. I checked on the net to learn more about
    the issue and found most people will go along with your views on this site.

  75. I will right away snatch your rss feed as I can not to find your email subscription hyperlink or e-newsletter service.
    Do you have any? Kindly let me recognise so that I could subscribe.

    Thanks.

  76. Hi there great blog! Does running a blog similar to this take a great deal of work?
    I have very little understanding of coding however I had been hoping to start my own blog in the near future.
    Anyway, should you have any recommendations or tips for new blog owners please share.
    I know this is off subject but I just needed to ask.
    Appreciate it!

  77. We stumbled over here different website and thought I might check
    things out. I like what I see so now i’m following you.
    Look forward to looking over your web page for a second time.

  78. Hello! I know this is somewhat off topic but I was wondering if you
    knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m
    having difficulty finding one? Thanks a lot!

  79. Hello to every one, the contents existing at this site
    are genuinely remarkable for people experience, well,
    keep up the nice work fellows.

  80. Quality articles is the important to invite the visitors to pay a quick visit the web page, that’s what this site is providing.

  81. Great web site you have here.. It’s difficult to find
    high quality writing like yours these days. I seriously appreciate individuals like
    you! Take care!!

  82. Hey there, I think your site might be having browser compatibility issues.
    When I look at your website in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.

    I just wanted to give you a quick heads up! Other then that, excellent blog!

  83. A person necessarily help to make significantly posts I might state.
    This is the very first time I frequented your web page
    and thus far? I amazed with the analysis you made to create
    this actual submit extraordinary. Magnificent task!

  84. Hey would you mind stating which blog platform you’re using?
    I’m going to start my own blog soon but I’m having a hard time choosing between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your layout seems different then most
    blogs and I’m looking for something completely unique.
    P.S My apologies for being off-topic but I had to ask!

  85. I have been surfing online more than 4 hours today, yet
    I never found any interesting article like yours.
    It’s pretty worth enough for me. In my opinion, if
    all site owners and bloggers made good content as you did, the web will be much more useful than ever before.

  86. Hi there, I found your site via Google whilst looking for a
    related topic, your web site got here up, it looks good.

    I’ve bookmarked it in my google bookmarks.
    Hi there, just changed into alert to your weblog via Google, and located
    that it’s truly informative. I’m gonna watch out for brussels.
    I’ll appreciate when you proceed this in future.
    Numerous other folks will be benefited out of your writing.
    Cheers!

  87. Hmm is anyone else experiencing problems with the pictures on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s
    the blog. Any responses would be greatly appreciated.

  88. Outstanding post but I was wondering if you could write a litte more
    on this topic? I’d be very grateful if you could elaborate a little bit further.
    Appreciate it!

  89. What’s up Dear, are you actually visiting this web site on a regular basis, if so afterward you will without doubt obtain fastidious know-how.

  90. For most up-to-date news you have to go to see
    web and on world-wide-web I found this web page as a most excellent site
    for most recent updates.

  91. Hey! I know this is kind of off topic but I was wondering which blog platform
    are you using for this site? I’m getting fed up of WordPress because I’ve had problems with hackers
    and I’m looking at options for another platform.
    I would be great if you could point me in the direction of a good platform.

  92. An impressive share! I’ve just forwarded this onto a friend who had been doing a little homework on this.
    And he actually ordered me lunch simply because I stumbled upon it for him…
    lol. So allow me to reword this…. Thank YOU for the meal!!
    But yeah, thanx for spending the time to discuss
    this topic here on your web site.

  93. I got this web site from my pal who shared with me about this
    site and now this time I am browsing this website and reading very informative content here.

  94. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I get in fact enjoyed account your blog posts.
    Any way I will be subscribing to your feeds and even I achievement you access consistently rapidly.

  95. I’m impressed, I have to admit. Seldom do I encounter a blog that’s both equally educative and entertaining, and let me tell you,
    you have hit the nail on the head. The problem is something which too few people are
    speaking intelligently about. I’m very happy that I found this
    during my hunt for something concerning this.

  96. Hi there! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

  97. I have been browsing online more than 3 hours today,
    yet I never found any interesting article like yours.
    It is pretty worth enough for me. In my opinion, if all
    site owners and bloggers made good content as you did, the web will be a lot more useful than ever before.

  98. Heya i am for the primary time here. I came across this board and I find It really
    useful & it helped me out a lot. I hope to offer something
    again and aid others like you aided me.

  99. Just wish to say your article is as astounding.
    The clarity in your post is just spectacular and i could assume
    you are an expert on this subject. Fine with your permission allow me to
    grab your feed to keep updated with forthcoming post.
    Thanks a million and please keep up the rewarding work.

  100. Exceptional post however I was wondering if you could write a litte more on this topic?
    I’d be very thankful if you could elaborate a little bit more.
    Appreciate it!

  101. Hello, Neat post. There is an issue together with your website in web explorer, may check
    this? IE nonetheless is the market chief and a good component to people will leave out your magnificent writing because of this problem.

  102. Hello! Do you use Twitter? I’d like to follow you if that
    would be okay. I’m undoubtedly enjoying your blog
    and look forward to new posts.

  103. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my
    newest twitter updates. I’ve been looking for a plug-in like this for quite some time
    and was hoping maybe you would have some experience with something like this.

    Please let me know if you run into anything.
    I truly enjoy reading your blog and I look forward to your
    new updates.

  104. Tudo bem? tenho uma pergunta completamente fora
    do tópico. Poderia me ajudar? Você sabe como tornar o seu site responsivo?
    É porque meu site parece estranho quando visualizado pelo meu
    SamsungS4. Estou tentando encontrar um modelo
    que seja capaz de resolver este contratempo. Se você
    tiver qualquer recomendação, por favor, compartilhe comigo, ok?
    Obrigado !

  105. 765530 860273Oh my goodness! a wonderful post dude. Several thanks Nonetheless We are experiencing dilemma with ur rss . Dont know why Can not sign up to it. Could there be anybody discovering identical rss difficulty? Anyone who knows kindly respond. Thnkx 92110

  106. You can definitely see your expertise within the work you write.
    The arena hopes for even more passionate writers such as
    you who aren’t afraid to say how they believe. Always go after your heart.

  107. I just like the helpful information you provide for your articles.
    I’ll bookmark your weblog and take a look at once more right here regularly.

    I am reasonably sure I’ll be told lots of new stuff right here!
    Good luck for the following!

  108. Hi, I do believe this is a great blog. I stumbledupon it 😉
    I will revisit once again since i have book-marked it.
    Money and freedom is the best way to change, may you be
    rich and continue to help other people.

  109. I just like the valuable info you supply on your articles.
    I’ll bookmark your blog and take a look at once more right here regularly.
    I am relatively certain I will learn plenty of new stuff right right here!
    Best of luck for the next!

  110. Cool blog! Is your theme custom made or did you
    download it from somewhere? A theme like yours with a few simple tweeks would really make my blog stand out.

    Please let me know where you got your design. Bless you

  111. Hmm is anyone else having problems with the
    pictures on this blog loading? I’m trying to find out if
    its a problem on my end or if it’s the blog. Any responses would be greatly appreciated.

Leave a Reply

Your email address will not be published. Required fields are marked *