Kotlin Basic Tutorial-Null value security

Source: Internet
Author: User

NULL security

An important feature of the Kotlin system is its commitment to eliminate null references. Avoid any NPE (nullpointerexception) exceptions.

Defining a variable that is allowed to be empty in Kotlin is not allowed to be defined in an empty way.

var a:string = "ABC"//Cannot be an empty

var b:string? = "ABC"//Can be empty
b.length//may error
//second one more than the first one '? '
Null value Check
Val L = if (b! = null) b.length () else-1
Secure call
B?. Length ()

If B is empty, returns without calling the length () Elvis operator

?:

Val L = b.length ()?: 1

If B is empty, then l=-1.

Check function parameters generally write this:

Fun foo (node:node): String? {
  val parent = Node.getparent ()?: return null
  val name = Node.getname ()?: Throw IllegalArgumentException ("name E xpected ")

  //...
}
!! Operator
Val b:string? = null
val L = b!!. Length
Safe conversion
Val aint:int? = A as? Int

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.