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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Metal and the Simulated Annealing Algorithm
  • Reactive Kafka With Spring Boot
  • Why You Should Migrate Microservices From Java to Kotlin: Experience and Insights
  • How To Create a Homescreen Widget in Android

Trending

  • Docker Base Images Demystified: A Practical Guide
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  • Scaling DevOps With NGINX Caching: Reducing Latency and Backend Load
  1. DZone
  2. Coding
  3. Languages
  4. Learning Kotlin: the Difference Between the Notnull Delegate and Lateinit

Learning Kotlin: the Difference Between the Notnull Delegate and Lateinit

Want to learn more about using the notnull and lateint delegates in Kotlin? Check out this post where we take a look at the advantages and disadvantages of both.

By 
Robert Maclean user avatar
Robert Maclean
·
Sep. 05, 18 · Presentation
Likes (6)
Comment
Save
Tweet
Share
12.3K Views

Join the DZone community and get the full member experience.

Join For Free

A lot of introductions to Kotlin start with how null is opt-in because that makes it safer — we even looked at this way back in post 8. The problem, however, is that sometimes we do not know what we want the value to be when we initialize the value, and we know that when we use it, we don't want to worry about nulls. The ability to change from null to never null might seem to be impossible, but Kotlin has two ways to do the impossible.

Before we look at the two solutions, let us look at a non-working example. Here, we have a class to represent a physical building, and we want to store the number of floors which we get from calling an API (not shown). The problem here is that there is no good default value. Let's look at a house with just a ground floor at 0, a multistory office building that could have 10 floors, and an underground bunker that could have -30 floors.

class Building() {
    var numberOfFloors : Int

    fun getBuildingInfo(erfNumber : String){
        // call municpality web service to get details
        numberOfFloors = 0; // 0 cause 0 = G like in elevators
    }
}

fun main(args:Array<String>) {
    val house = Building()
    house.getBuildingInfo("123")
    println("My house, up the road, has ${house.numberOfFloors}")
}


This will not compile as it states Property must be initialized or be abstract for the number of floors.

Notnull

Fom our previous delegates, we have the notnull delegate. We can use the notnull delegate to allow the property to not be set initially. And, then:

import kotlin.properties.Delegates

class Building() {
var numberOfFloors : Int by Delegates.notNull()

fun getBuildingInfo(erfNumber : String){
// call municpality web service to get details
this.numberOfFloors = 10;
}
}

fun main(args:Array<String>) {
val house = Building()
house.getBuildingInfo("123")
println("My house, down the street, has ${house.numberOfFloors}")
}


This example will print out that we have 10 floors. If we were to comment out line 14, we would get the following exception: Exception in thread "main" java.lang.IllegalStateException: Property numberOfFloors should be initialized before get So, this is not exactly a null exception but close enough that it makes no difference.

Lateinit

Another option is lateinit, which we can add before the var keyword. But, we cannot use it with Int or other primitive types, so we need to change that as well to a class. This is a really nice and simple solution.

data class Floors(val aboveGround: Int, val belowGround: Int)

class Building() {
    lateinit var numberOfFloors : Floors

    fun getBuildingInfo(erfNumber : String){
        // call municpality web service to get details
        this.numberOfFloors = Floors(2, 40);
    }
}

fun main(args:Array<String>) {
    val house = Building()
    house.getBuildingInfo("123")
    println("My house, in the middle of the avenue, has ${house.numberOfFloors}")
}


Once again, if we comment out line 14, we get an exception as expected: 'Exception in thread "main" kotlin. UninitializedPropertyAccessException : lateinit  property  numberOfFloors has not been initialized'.

Lateinit Vs. Notnull

As we can see in these simple examples, both methods achieve the same goal, but they both have their own limitations and advantages:

  • notnull being a delegate needs an extra object instance for each property, so there is a small additional memory/performance load.
  • The notnull delegate hides the getting and setting in a separate instance, which means anything that works with the field, for example, Java DI tools, will not work with it.
  • lateinit doesn't work with primitive types (Int, Char, Boolean etc...) as we saw above.
  • lateinit only works with var and not val.
  • When using lateinit, you gain access to the .isInitialized method, which you can use to check if it was initialized.
Kotlin (programming language)

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

Opinions expressed by DZone contributors are their own.

Related

  • Metal and the Simulated Annealing Algorithm
  • Reactive Kafka With Spring Boot
  • Why You Should Migrate Microservices From Java to Kotlin: Experience and Insights
  • How To Create a Homescreen Widget in Android

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!