kotlin foundation null check

NULL check mechanism

Kotlin air safety design parameters for the statement may be empty, when in use to be empty judging process, there are two approaches, the field plus !! like Java throw an empty exception, after adding another field? Can not do or with the process returns null value:? short determination processing

// ? Represents back type plus empty 
var Age:? String = "23" // throws a null pointer exception 
Val AGEs = Age !! .toInt ()
 // do processing returns null 
Val ages1 = Age? .ToInt ()
 // Age returns null -1 
Val ages2 = Age .toInt ():?? -1

 

When a reference value may be null, corresponding to the type declared it must be clearly marked as null.

When the content of the string str is not an integer, return null:

fun parseInt(str: String): Int? { // ... }

The following example demonstrates how to use a null return value may be a function of:

main Fun (args: the Array <String> ) {
   IF (args.size <2 ) { 
    Print ( "Two integers expected" )
     return 
  } 
  Val X = the parseInt (args [0 ]) 
  Val Y = the parseInt (args [. 1 ])
   // directly `x * y` cause errors, because they may be null. 
  IF (x! = null && y! = null ) {
     // after performing the check through a null value, the type of x and y will be automatically converting non-null variable 
    Print (X * Y) 
  } 
}

 

Guess you like

Origin www.cnblogs.com/superxuezhazha/p/12028320.html