Learning Kotlin (3) and type nullable type systems

1. Type System

Using the type system, the compiler may check meaningless, invalid, an error code type mismatch and the like.
In addition, static type checking can also provide useful information to the compiler.

And compared to Java, Kotlin removed the original type, only packaging types , the compiler when compiling stage, let the compiler to optimize their own performance, the type of packaging unpacking into basic types.
Kotlin nullable type is introduced, it is possible to null value is represented by a separate nullable type, it can be divided so that a clear line between the null and non-null reference can be cited.
kotlin type hierarchy shown in Figure 3-2:
Here Insert Picture Description
you can see, String, Int, MyClass inherited their non-empty type, that is, they can be boxed into a String? , Int? , MyClass? . While at compile time, they also may be unpacking into a string, int, myclass, time will be saved to the stack of storage space.

If we can show the definition of the empty type, it will greatly reduce the compiler at compile time or runtime null pointer exception.

In the kotlin === determines whether the same memory space pointed && values are identical , == determines whether the same value , for example:

//例子1:
 val a:Int = 1000
 val b:Int = 1000
 >>>a === b 
 true
 >>>a == b
 true

//例子2:
 val a:Int? = 1000
 val b:Int? = 1000
 >>>a == b
 true
 >>>a === b
 flase

In the first example, a and b are Int, at compile time to unpack int, a value of "1000" is the presence of the stack space, and it also has a, b two reference points a and b so that the memory space is the same.
The second example, a and b are Int? , At compile time, they will be seen as two different objects in different space allocated on the heap, so they point to the memory address is not the same.

In Java array type T [] (long [], int [] ...}), whereas in the Kotlin, directly represented by Array array type , for example, we constructed an array of int 5 elements, the initial value of each element as i * i:

val squareArray = Array(5, {i -> i * i})
>>> squareArray.forEach(::println)
0
1
4
9
16

Java, on Kotlin in eight basic types of arrays with new xxxArray defined. (Such as BooleanArray, ByteArray, DoubleArray ...)

2. nullable type

Java is used in the Optional orElsebe sentenced empty, but to use unsightly.
Kotlin in use ?.安全调用符, ?:Elvis操作符. for instance:

fun main(args: Array<String>){
  println(getLength(null))
  println(getLength("hello"))
}

fun getLength(s: String?):Int{
   return s?.length ?: 0       //如果s不为空,就返回 s.length,否则就返回0
}

3. Security Operators

null types areNothing?
in Kotlin, a multi-use ?, you can avoid a lot of empty sentenced operation:

val str:String = null        //编译报错,因为String不能为空
var nullStr:String? = null       //编译通过
null == null                 //返回true
null is Any                  //返回false
null is Any?                 //返回true
var a = null  
>>>a                        //输出null
a = 1                       //编译报错,因为null的类型Nothing? 而1是Int,不能向上转型

We can not directly call the nullable type or method of its properties , for example, the following code directly given:

nullStr.length        //编译报错

nullStr?.length       //要用安全调用符 ?. 编译才正确

!!非空断言Nullable types such object can call the method or attribute member:

nullStr = null
>>>nullStr!!.lenth //如果nullStr为空,则抛出空指针异常
....Expection

4. Special Type

4.1 Unit Type

Kotlin in the Unittype implements and Java in voidthe same function
Here is the definition of Unit

public object Unit{                 //Unit类型是一个object对象类型
  override fun toString() = "kotlin.Unit"  //如果println输出对象类型,就是"kotlin.Unit" 
}

When a function does not return a value, we will use Unit, return Unit and do not show, or declare a return type of the function for the Unit .
The compiler will infer it, so for us, quite Unit is the default.

4.2 Nothing with Nothing? Type

In Java, if you want a function return value will always be null, then you can write the function's return type is void of boxing class Void, and returns null
and this Voidwould correspond in Kolin Nothing?, the only return that can be accessed value is null
in Kotlin types of systems, Nothingis the bottom, private constructors in its described which can not be instantiated.
** If the return value of a function is Nothing, which represents the function will never be the return value. ** Java and void as of

Nothing we can return value of the function to throw an exception

Nothing of difference and Unit:
Unit is the return type Unitof
but Nothing is without any type of return

The difference between Nothing and Nothing: The?
Nothing? Type except null, the other can not be assigned.
And Nothingcan not be assigned.

4.3 Any and Any? Type

Any?Empty type hierarchy is the root, Any? Any parent is.

>>> 1 is Any         //Int类型的1是Any
true
>>> 1 is Any?        //Int类型的1是Any?
true
>>>null is Any       //null不是Any类型
false
>>> null is Any?     //null是Any?
true
>>>Any() is Any?     //Any()是Any?类型
true

The type conversion type detector and

In general, no need to use the display in Kotlin conversion operator, because the compiler and inspection is automatically converted when needed.

5.1 is operator

is operator can check the object A is compatible with a particular type of X (X is the type A or type X derived classes), and Java, and instanceOf()almost
in kotlin, we can use is, may be used!is

5.2 Auto Switch

Automatic conversion kotlin is this posture:

   fun strlen(ani: Any): Int {
        return when (ani) {
            is String -> ani.length
            is Number -> ani.toString().length
            is Char -> 1
            is Boolean -> 1
            else -> {
                print("Not a string")
                -1
            }
        }
    }
    ...
    
     val len = strlen("abc")
     print(len) //3
     val lens = strlen(1)
     print(lens) //1

5.3 as operator

as operator is used to perform a reference type of explicit type conversion
if the conversion is compatible with the type of conversion is successful, otherwise use as? operator will return null

    open class Foo       //父类Foo
    class Goo : Foo()      //子类Goo
    
    val foo = Foo()
    val goo = Goo()
    foo as Goo  //运行报错,父类型不能强制转化为子类型
    foo as? Goo  //返回null
    goo as Foo //子类型可以转化为父类型

Strong rotor parent class is a violation of the principle of Leeb replaced.

Published 248 original articles · won praise 99 · Views 100,000 +

Guess you like

Origin blog.csdn.net/rikkatheworld/article/details/102831276
Recommended