Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Subbu Lakshmanan
Subbu Lakshmanan

Posted on • Edited on

     

Simple, yet powerful features of Kotlin

I read about Kotlin, the simple, yet powerful language which can be Java alternative years ago when Jetbrains released their initial versions of Kotlin. Having worked on Java for longer time, I called it "blasphemy", and totally ignored it.

However ever since theKotlin was announced as offical programming language for Android inGoogle I/O, I realized that I have been silly all these time and biased towards Kotlin. I felt stupid for not realizing it sooner and have started spending time in learning Kotlin.

I'm currently going through the pluralsight course,Kotlin Fundamentals byKevin Jones. As he was explaining "How Kotlin Improves the Handling of Null Values", I realized the simple, yet powerful feature of Kotlin in handling the 'null' and how it can help java developer fromfrustrating null check.

Funny Null Pointer

In Java

In Java by default any variable declared can benull. For example,

classDeveloper{Stringteam;Stringrole;Stringproject;voiddisplay(Stringname,StringemployeeType){if(employeeType.equals("Full-Time")){System.out.println(name+" is a Full-Time "+role+" in "+team+" working in "+project);}else{System.out.println(name+" is a Intern "+role+" in "+team+" working in "+project);}}}classLearningKotlinUtil{publicstaticvoidmain(String[]args){Developerdev=newDeveloper();dev.project="ePhone7";dev.team="Mobile Team";dev.role="Android Developer";dev.display("Subbu","Full-Time");dev.display("Subbu",null);}}
Enter fullscreen modeExit fullscreen mode

In theDeveloper class,type can be null. So the second invocation to 'display()' method will throw aNullPointerException. To avoid that, the developer has to donull-check as below.

classDeveloper{...voiddisplay(Stringname){if(employeeType!=null&&employeeType.equals("Full-Time")){...}else{...}}}
Enter fullscreen modeExit fullscreen mode

or you can write as below,

classDeveloper{...voiddisplay(Stringname,StringemployeeType){if("Full-time".equals(employeeType)){...}else{...}}}
Enter fullscreen modeExit fullscreen mode

To take advantage of IDE features, the developer can annotate the variabletype with@NonNull annotation as below.

classDeveloper{...voiddisplay(Stringname,@NonNullStringemployeeType){if(employeeType!=null&&employeeType.equals("Full-Time")){...}else{...}}}
Enter fullscreen modeExit fullscreen mode

@NonNull annotation is supported through android annotation support library or Java 8 Annotation Support JSR-308.
import android.support.annotation.NonNull;

Now the IDE (Intellij/Android Studio) warns the developer as in the below screenshots,
Assigning Null
Null-Check

However it doesn't prevent the variable 'type' being set to 'null' and the developer must listen to the IDE(if using one) warnings. If the developer isn't careful, the null-pointer can only be realized in runtime.

Kotlin to Rescue

InKotlin,by default the variablesvar is ofnon-null type thetype system defines whether the variables can hold 'null' or not. For example, here when you declare employeeType as 'employeeType: String', the Kotlin type system enforces employeeType variable as non-nullable.

classDeveloper{varteam:String=""varrole:String=""varproject:String=""fundisplay(name:String,employeeType:String){if(employeeType=="Full-Time"){println("$name is a Full Time $role in $team working in the $project project")}else{println("$name is a Intern $role in $team working in the $project project")}}}funmain(args:Array<String>){valdev=Developer()dev.team="Mobile Team"dev.role="Android Developer"dev.project="ePhone7"dev.display("Subbu","Full-Time")}
Enter fullscreen modeExit fullscreen mode

Now the parameter, 'employeeType' can never benull and attempting to do so will result incompilation error.

funmain(args:Array<String>){valdev=Developer()dev.team="Mobile Team"dev.role="Android Developer"dev.project="ePhone7"dev.display("Subbu","Full-Time")dev.display("Subbu",null)}
Enter fullscreen modeExit fullscreen mode

Compilation Error

If you really want to allow employeeType to accept 'null' values, you must explicitly states so as below using'?' operator.

If the 'employeeType' variable can have 'null' values, it should be declared as 'String?' as per the Kotlin Type system.

classDeveloper{...fundisplay(name:String,employeeType:String?){...}}
Enter fullscreen modeExit fullscreen mode

The declaration 'employeeType: String?' tells that the compiler that employeeType can accept 'null' as value. This is equivalent to@Nullable annotation in java.

This is one of the powerful features of Kotlin. Making the variables as 'Non-Null' by default and forcing the developer to explictly declare variables that can be 'null',
1. Indirectly forces the developer to think about the variables usage when declaring one
2. It prevents the developer attempting to assign/pass 'null' in compilation time itself.

I have just kick-started learning Kotlin, and I will keep posting new simple, yet powerful features of Kotlin as I explore them.

In my humble opinion, a better understanding of Kotlin type system will greatly assist the developer to think about the values that a variable can hold at the declaration and also prevent other developers to pass/assign 'null' values even by mistake.

I have just kick started learning Kotlin, and I will write further blogs about the features that I liked, once I understood them completely. Please feel free to throw in any comments or suggestions.

Top comments(7)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
vladrassokhin profile image
Vladislav Rassokhin
  • Joined

In Kotlin, by default the variables var is of non-null type.
If you really want to allow type to accept 'null' values, you must explicitly states so as below using '?' operator.

Please do not misinform readers, it notby default and definitely not an'?' operator. (Operators cannot be applied to types). It's part of type system where '?' in the end of type denotes reference as nullable and without - non-null references.
Here's proper explanation of nullability in Kotlin.

Actually nullability-related operators are?.,!!.,?: andas?.

CollapseExpand
 
nebtrx profile image
Omar 👾λmed
  • Joined
• Edited on• Edited

Agreed. That's harsh!. Anyway,String? is actually syntactic sugar for something likeNullable<String>. It's an idea taken fromMaybe polymorphic data type, which is very popular in Functional Languages like Haskell.

CollapseExpand
 
humzakhan profile image
Humza K.
Full Stack Dev in Fintech. AWS Certified Solutions Architect. Enthusiastic about Startups & Entrepreneurship. https://twitter.com/humzakh_
  • Location
    Montreal, Canada
  • Work
    Full Stack Developer at TickSmith Corp
  • Joined

"Please do not misinform readers" That's harsh. He didn't do it intentionally. As he mentioned, he's currently learning the language himself. Why are you being intentionally rude then?

CollapseExpand
 
subbramanil profile image
Subbu Lakshmanan
Enthusiastic programmer, working as Android developer building custom Android Images (AOSP) and apps.

Thank you Vladislav Rassokhin for the feedback. I have updated the blog as per the comments.

CollapseExpand
 
dean profile image
dean
i write code
  • Location
    Washington, USA
  • Pronouns
    any
  • Joined
• Edited on• Edited

I love Kotlin and I have for a while. One of my favorite features is not just null-safe types, but how it handles nullable types! The.? (null-safe.) operator is amazing, as well as the?: (if null then...) operator. I'd give examples of them, but that's for a whole new blog post :)

CollapseExpand
 
subbramanil profile image
Subbu Lakshmanan
Enthusiastic programmer, working as Android developer building custom Android Images (AOSP) and apps.

I have just started learning Kotlin and I love it. I will check out the 'null-safe' operator. And absolutely I'd love to see your new blog post. :)

CollapseExpand
 
niharmore33 profile image
nihar
  • Joined

Let’s take a look at the things you need to know about ‘Kotlin: The Latest Powerful Language to Streamline Android App Development’.
Learn Kotlin here:hackr.io/tutorials/learn-kotlin

How is Kotlin different from Java?

Well, case studies have shown the main reason is that it represents a cleaner approach to app development, and will likely serve as a better entry for new Android developers. It also help developers in number of instances like:

Concise

Kotlin eliminates null references for example and it doesn’t have checked exceptions – both of which can save developers from head crunch. As you’ll see, various new features of Kotlin also allow us to get rid of boilerplate code too, resulting in leaner and more readable programs.

Kotlin_BrainMobiBlogs

Kotlin Extensions for Android

Tired of using findViewById and started using the famous Butterknife library. Then you will love Kotlin Android Extensions too. The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of the popular libraries but without having to add any extra code or shipping any additional runtime. Here is a simple example to showcase the incredible flexibility offered by Kotlin. Just create a Kotlin file and paste the following snippet in it:

Kotlin_BrainMobiBlog

Performance

A Kotlin application runs as fast as Java, thanks to very similar bytecode structure. With Kotlin’s support for inline functions, code often runs even faster than the same code written in Java.

Learning curve

For a Java developer, getting started with Kotlin is very easy. The automated Java to Kotlin converter included in the Kotlin plugin helps with the first steps. Kotlin Koans offer a guide through the key features of the language with a series of interactive exercises.

Safe

Avoid entire classes of errors such as null pointer exceptions. Get rid of those pesky NullPointerExceptions, you know, The Billion Dollar Mistake.

Safe_BrainMobiBlogs

Interoperable

Kotlin is 100% interoperable with Java, allowing to leverage existing libraries for JVM, Android and the browser in a Kotlin based application. This includes annotation processing, so data binding and Dagger work too. Means Kotlin can call Java, and Java can call Kotlin.

BrainMobi_Blog
BrainMobi_Blog

In our next blog, we will discuss in brief some of the advantages which Kotlin offers over Java.

Why are developers excited about Kotlin support?

Kotlin is a perfect fit for top Android developers to embrace while building exemplary Android apps. It’s a statically typed programming language for modern multiplatform applications and offers a whole new work experience. Other than the whole new experience, Kotlin also offers some great methods explained above to make great cuts on unnecessary burdens. The code written with Kotlin is simpler than the Java equivalent, even when it references the same libraries or classes. It makes debugging a breeze.

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Enthusiastic programmer, working as Android developer building custom Android Images (AOSP) and apps.
  • Location
    Dallas, Tx
  • Education
    Masters of Computer Science
  • Joined

More fromSubbu Lakshmanan

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp