###Kotlin data type

# # # # Boolean type

We define a Boolean variable b with the following code:

val b: Boolean = true
Copy the code

Booleans are mostly equivalent to Java booleans, but sometimes booleans are boxed into Java booleans, but this is automatically determined by the compiler and we don’t need to worry about it. (The same goes for other types.)

# # # # Number type

The numeric types in Kotlin are as follows:

Points to note:

  • MAX_VALUE, etc. (and so on)
  • As in Java, when the type is not clear, you can add L and F to identify; You can use scientific notation
  • We can use binary equality to represent values, for example, we can use 0b00000011 to represent 3 of Int
  • NaN (Not A Number) is printed when the value is incorrect, such as 0/0. NaN is Not A comparison.

##### Type conversion

In Java, implicit type conversions are supported, for example:

int i = 1;
long l = i;
Copy the code

When Kotlin types are converted, they cannot be converted implicitly, they must be converted explicitly, for example:

Val I: Int = 1 val L: Long = 1L fun main(args: Array<String>) {// Error L = I // correct L = i.t Long()}Copy the code

#####Kotlin does not distinguish between boxed and unboxed types

In Java, we often need to do boxed and unboxed, for example:

Integer i1 = new Integer(1);
int i2 = 1;
Copy the code

However, Kotlin does not distinguish between boxed and unboxed types, and the compiler automatically converts them for us.

# # # # Char type

The Char type corresponds to Character in Java and is a two-byte Unicode Character of 16 bits.

Val c1: Char = '\u000f' val c: Char = '0'Copy the code

Characters are enclosed in single quotes and can be common characters, encodings (not strings), escape characters.

Kotlin’s escape characters are as follows:

# # # # String type

It’s essentially a string of Char types, in double quotes.

##### Here is how strings are created

Val s1: String = "love" val s2: String = String(charArrayOf('l', 'o', 'v', 'e')Copy the code

##### string comparison (note contrast with Java)

// Equals println(s1 == s2) // Equals println(s1 === s2)Copy the code

##### String template

/ / Java, joining together very troublesome println (" "+ a + + +" = "b" + "+ (a + b)) / / Kotlin, very convenient. Println ("$a+$b=${a + b}")Copy the code

######Tips: The $sign can be output by escaping the $character

##### original character

The original character is enclosed in triple quotes, and the character is printed unchanged:

Val I: Int = 10000 val rawStr: String = """ I love you $I year """ println(rawStr)Copy the code

#### Null type safety

Let’s start with the Java code:

public static void main(String[] args) {
    System.out.println(getName().length());
}

public static String getName() {
    return null;
}
Copy the code

If the getName() method is someone else’s library and doesn’t have the source code, the compiler doesn’t know if it’s null, so there’s a null pointer danger.

Here is an example of Kotlin’s code:

fun getName(): String {
    return null
}
Copy the code

So we can’t return null, so we can safely use the return value of getName() :

fun main(args: Array<String>) {
    println(getName().length) 
}

fun getName(): String {
    return "str"
}
Copy the code

##### an omitted version of the null sentence

As you can see, this will not compile at all. If we do need to return null, we need to add a question mark:

fun getName(): String? { return null } fun main(args: Array<String>) { val name = getName() ? : Return // This is equivalent to: //if (name == null) {//if (name == null) {//if (name == null)}Copy the code

##### if we are sure the code is not null

val str: String? = "haha" // Tell the compiler to compile println(STR!! .length)Copy the code

##### a safe call that returns null when an object is empty without firing a null pointer

val str: String? = null // Println (STR? If (STR == null) {// println(null) //} else {// println(str.length) //}Copy the code

#### Intelligent type conversion

In Java, if a type is evaluated, it needs to be converted:

Parent p = new Child();
if (p instanceof Child) {
    ((Child) p).say();
}
Copy the code

In Kotlin, if the type is judged, no conversion is required:

Val p: Parent = Child() if (p is Child) {// if (p is Child)Copy the code

#### Secure type conversion

Val p: Parent = Parent() val c1: Child? Return null val c2: Child? = p as? ChildCopy the code

# # # # range

The intervals in Kotlin are subclasses of ClosedRange, commonly used are:

  • IntRange
  • CharRange
  • LongRange
  • ComparableRange

Let’s take a look at the ClosedRange implementation:

public interface ClosedRange<T: Comparable<T>> {
    /**
     * The minimum value in the range.
     */
    public val start: T

    /**
     * The maximum value in the range (inclusive).
     */
    public val endInclusive: T

    /**
     * Checks whether the specified [value] belongs to the range.
     */
    public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive

    /**
     * Checks whether the range is empty.
     */
    public fun isEmpty(): Boolean = start > endInclusive
}
Copy the code

Sample code:

Fun main(args: Array<String>) {//[0,100] val r1: IntRange = 0.. 100 //[0,101] = [0,100] val r2: = 0 until 101 IntRange = 0..-1 println(r1.start) println(r1.endinclusive) // Whether println(r1.contains(50)) println(50 in) For (I in r1) {println("$I,")}}Copy the code

Operator overloading: operator overloading: operator overloading

public operator fun contains(value: T): Boolean = value >= start && value <= endInclusive
Copy the code

# # # # array

Sample code:

Val arr: IntArray = intArrayOf(1, 2, 3, 4, 5, 6, 7) // Uncustomized array val arr1: Array<Int> = arrayOf(1, 2, 3, 4, 5, 6, 7) Array<Man> = arrayOf(Man(" Li "), Man("张"), Man(" u ")) println(arr.size) Println (arr.joinToString(",")) // Intercepting. Note that an interval is passed in. (Note that strings also support this operation.) For (I in arr) {println(I)}Copy the code

If you feel that my words are helpful to you, welcome to pay attention to my public number:

My group welcomes everyone to come in and discuss all kinds of technical and non-technical topics. If you are interested, please add my wechat huannan88 and I will take you into our group.