1. 程式人生 > >Say goodbye to NullPointerException. Working with nulls in Kotlin (KAD 19)

Say goodbye to NullPointerException. Working with nulls in Kotlin (KAD 19)

It had taken me too long to write an article to one of the most important parts of Kotlin: the treatment of nullity.

Tony Hoare, the creator of the idea of nulls, calls itself “the billion dollar mistake”. Nulls are one of the most error-prone points you get when you are coding with Java.

If you look at your bug manager, I’m sure that +90% of the errors you see are NullPointerException

.

Thanks to Kotlin, you’ll work in a much safer environment (even with Java libraries), which will minimize these problems.

Nulls in Kotlin

Nulls in Kotlin don’t exist until you say otherwise.

That is, no variable, by default, can be set to null. Remember that in Kotlin all types are objects.

Therefore, this won’t compile:

1 valx:Int=null

Want to learn Kotlin?

Check my free guide to create your first project in 15 minutes!

If you want a variable to accept nulls, you have to mark the type with a ?:

1 valx:Int?=null

Compile-time check

But, from that point on, the compiler will force you to check the null before doing anything with the variable. This ensures that a NullPointerException doesn’t occur.

For example:

1 valy=x.toDouble()

It won’t compile, if you don’t check first if it’s null:

123 if(x!=null){valy=x.toDouble()}

Secure access expression

There is an easier way to represent the previous example, which is to use a ? in before the . when calling a method.

If the variable isn’t null, it’ll execute the operation. Otherwise, it won’t do anything:

1 valy=x?.toDouble()

In this case, if x is null,  then the expression willl return null as well. So y will be of type Double?.

The Elvis operator

But what if we don’t want to have a nullable variable as a result of the operation? The Elvis operator (?:) allows us to return a value in that case:

1 valy=x?.toDouble()?:0.0

This code would be equivalent to:

12345 valy=if(x!=null){x.toDouble()}else{0.0}

Spoiler: As you see, most of the sentences in Kotlin are in turn expressions. For example, you can assign the result of an if to a variable.

Avoiding the null check

There is an operator (!!) that will avoid the need to check null if you’re completely sure that a variable will never be null.

In my opinion, there are very few cases where this operator makes sense. There is almost always a better solution.

But you could do the following:

12 valx:Int?=nullvaly=x!!.toDouble()

This would compile and produce a NullPointerException

What I said: be very careful with this operator.

Java support

When we’re working with Java libraries, we may find ourselves facing different situations regarding null checking.

The library is properly annotated

If the @Nullable and @NotNull annotations are being used properly, both Java and Android ones, Kotlin will be able to work seamlessly with them and figure out when a variable is null and when not.

Many parts of the Android framework are already annotated correctly, so this is a huge advantage to working with Kotlin.

The library has no annotations

However, if the library isn’t annotated, the types will be marked with a special operator (a unique !), which means that it’s in our side to decide if a parameter or return value accepts null or not.

If we have access to the source code, it’s best to check if the code we are using allows nullity or not to make this decision.

An example on Android that isn’t annotated is the RecyclerView support library. When you create an adapter and generate the methods, by default it’ll add an interrogation to the types.

But if you look at the source code, you’ll realize that nothing can be null in the methods you need to override. So you can get rid of all the interrogation signs, and avoid unnecessary null checks.

Conclusion

The NullPointerException are a nightmare for all Java developers, and surely represent most of the errors that occur in your code.

Reducing your number in Kotlin to near zero is very easy, even when working with libraries and frameworks in Java.

Only this will avoid you hours and hours of unnecessary debugging, plus it’ll make the code much more stable.

If you want to learn a lot more about all this and get enough fluency to create your own Android Apps, I recommend that you take a look at the free guide to learn how to build your first project, or just get the book and learn how to create a complete App from scratch.

I’m in love with Kotlin. I’ve been learning about it for a couple of years, applying it to Android and digesting all this knowledge so that you can learn it with no effort.

Shares

Like this:

Like Loading...

相關推薦

Say goodbye to NullPointerException. Working with nulls in Kotlin (KAD 19)

It had taken me too long to write an article to one of the most important parts of Kotlin: the treatment of nullity. Tony Hoare, the creator of the i

Functional operations with collections in Kotlin (KAD 11)

I must admit that, for me, one of the most frustrating things when writing Java ccode is the list handling. Java 8 has some improvements in this resp

AppBoxFuture(二): Say goodbye to sql!

  資訊管理類應用系統離不開關係資料儲存,目前大家基本都使用的是傳統的資料庫如MySql、Postgres等。作者從事資訊化建設十多年,個人認為傳統的資料庫存在以下的問題: 擴充套件問題:   系統資料的不斷增長是個繞不過去的坎,傳統資料庫的儲存結構一般都基於B+tree,單表資料在一定範

軟考總結——say goodbye to you~

背景 經歷了三個月的軟體設計師的準備,終於終於我們考完了!這段時間過的可是無比充實,每天都很開心,已經習慣了每天早上打完卡之後八點準時在釘釘群裡等著接收組長安排的“今日任務”,今日任務今日畢的感覺非常爽!雖然期間還接受了一點小獎勵,但是絲毫不影響我們學習的激情!一晃三個月的時間就過去了,和小

Working with JSON in Swift

Extracting Values from JSON The JSONSerialization class method jsonObject(with:options:) returns a value of type Any and throws an error if the data cou

Working With Video in iOS: AVFoundation and CoreMedia

Step 3: Conform to UIImagePickerControllerDelegateIf you tap the record button, you will see that the expected default recording behaviour is available to

Say goodbye to findViewById. Say hello to Data Binding Library.

findViewById is one of the most annoying boilerplate code in Android application development. This part of code unnecessarily requires bu

Working with JSON in C#

JavaScript Object Notation (JSON) is a way of representing data structures in a “human-readable” form that can be used to exchange infor

【 Vivado 】Working with Sources in Non-Project Mode

與為您管理原始檔的專案模式不同,原始檔在非專案模式下由您控制。 使用Tcl命令,指定要處理和輸出要生成的檔案的檔案,包括網表,位元流和報告檔案。 專案模式和非專案模式命令顯示常用的專案模式命令和相應的非專案模式命令。 For more information on Project Mode

[PWA] Add Push Notifications to a PWA with React in Chrome and on Android

On Android and in Chrome (but not on iOS), it's possible to send push notifications with a PWA. We'll start by asking the user for permission to send them

Openwrt working with patches in the build system (8)

Reference :https://openwrt.org/docs/guide-developer/build-system/use-patches-with-buildsystem example:   in the kernel top-level directory   # quilt new

Course to Get Started with XGBoost in Python

Tweet Share Share Google Plus XGBoost With Python Mini-Course. XGBoost is an implementation of g

Kotlin Android Extensions: Say goodbye to findViewById

If you’ve been developing Android Apps for some time, you’re probably already tired of working with findViewById in your day-to-day life to recover v

Introducing Protocols: Say goodbye to bad data · Segment Blog

You can’t make informed decisions when you don’t trust your underlying data. Unfortunately, finding data mistakes is far too common for most companies. Whe

Writing a RecyclerView Adapter in Kotlin (KAD 16)

An interesting way to see how Kotlin simplifies your life is by creating a RecyclerView Adapter. You’ll see that the code can be organized in such a

How to create own operator with python in mxnet?

處理 需要 調用父類 rgs rop 數據類型 賦值 創建 recipe 繼承CustomOp 定義操作符,重寫前向後向方法,此時可以通過_init__ 方法傳遞需要用到的參數 1 class LossLayer(mxnet.operator.CustomOp):

Working with the Dynamic Type in C#

called efi another strings offer member XML 圖片 eps Working with the Dynamic Type in C# https://www.red-gate.com/simple-talk/dotnet/c-pro

Failed to find target with hash string 'android-26' in

是因為 專案使用 Android 26 但是 SDK並沒有安裝,使用了其他版本 參考 https://blog.csdn.net/ThePromonkeyOf_HeLuo/article/details/78518701 去SDK Manager中下載相應的api,之後從新編譯即可。新版Android

Failed to find target with hash string 'android-26' in

是因為 專案使用 Android 26 但是 SDK並沒有安裝,使用了其他版本 參考 https://blog.csdn.net/ThePromonkeyOf_HeLuo/article/details/78518701 去SDK Manager中下載相應的api,之後從新編譯即可。新版

[Bug集合]VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in...

VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future 網上各種解決好像都不行,感覺可以試一下這個 https://st