Hands on learning Kotlin - data types

Keywords: Mobile Java Attribute

This series is suitable for students who have not learned Kotlin at all and are like quick start students. I am also learning now, so there will be mistakes as notes. If I understand it wrong or have questions, I sincerely hope that you can discuss it in the message area.

data type

1. Boolean type
val b:Boolean=true

Definition type format: access modifier modifier object name: class name = specific assignment

There are two modifiers for variables:

  • val immutable property declaration
  • var variable attribute declaration

val decoration is similar to the final decoration in java. It must be initialized (or in the construction method or init {}) method when defining, but not the same Kotlin constant is decorated with const. Note that immutable property is not static property

var is a variable attribute, which can be uninitialized and assigned multiple times

Unlike java, basic data types can be declared in lowercase boolean in kotlin. It must be defined by its packing class. The access modifier defaults to public(java is defualt)

2. Number type
val l:Long=1231231L
val l1:Long=1231231
val l2:Long=1231231l//error
val f:Float=3f
val f1:Float=3.0F
val f2:Float=3.0//error
val d1:Double=3.0
val s:Short=12712
val byte:Byte=127

In java, there is a packing type Integer corresponding to the basic data type int. in Kotlin, which does not have this concept, int in Kotlin is equivalent to the combination of int and Integer. The compiler will help me choose it. There is no implicit conversion in Kotlin, such as:

        short s = 0;
        int i = 0;
        long l = 0;
        i = s;
        l = i;
        l = s;

Correct in java in Kotlin

    val s: Short = 0
    var i: Int = 0
    i = s.toInt()
    i = s//error
3. Char type

Basically consistent with java, here are some commonly used escape characters

Escape character Meaning
\t Tab character
\b Cursor back one character
\n Enter
\r Cursor back to the beginning of line
' Single quotation mark
" Double quotation marks
\ Backslash
$ Dollar sign, Kotlin supports character templates beginning with dollar sign
4. String type
  • = = = = = = = =
val str: String = "str"
val str1: String = String(charArrayOf('s', 't', 'r'))

fun main(args: Array<String>) {
    println(str== str1)
    println(str=== str1)

}

//Result: 
true  
false

In Kotlin = = equivalent to. equals() object comparison equality===

  • String template
    val int1: Int = 1
    val int2: Int = 2

    println(" " + int1+ " + " + int2 + " = " + (int1 + int2))
    println("$int1 + $int2 = ${int1 + int2}")

    //hello "world"
    //Escape characters mentioned earlier
    println("hello \"world\"")
    val s:String="""

        \t
        \n
        hello World
    """
    println(s)

//Result:  
1 + 2 = 3
1 + 2 = 3
hello "world"

        \t
        \n
        hello World
"${}" string template "" "" "" original string  
5. Classes and objects

Direct theory is not intuitive enough, so direct code:

class Beauty private constructor(val character: String, val looks: String, val voice: String) {//1
    constructor(character: String, looks: String, voice: String, Three circles: String) : this(character, looks, voice)//2 
    constructor(character: String, looks: String) : this(character, looks, "Pleasant to hear")
}

class Handsome guy(character: String, looks: String, voice: String) : people(character, looks, voice) {//3
    init {//4
        println("Handsome guy: character:$Character, appearance:$Look, sound:$voice")

    }

}

class Test{//5
    val d: Double
    val i: Int

    constructor(double: Double, int: Int) {
        d = double
        i = int
    }

    constructor(double: Double) {
        d = double
        i = 0
    }

}

open class people(val character: String, val looks: String, val voice: String) {
    init {
        println("new One. ${this.javaClass.simpleName}: character:$Character, appearance:$Look, sound:$voice")

    }

    fun funA() {
        println(this.voice)//6
    }
}

fun main(args: Array<String>) {
    val My favorite girl: Beauty = Beauty("Tender", "Sweet", "Pleasant to hear","Three circles")
    val The man I worship: Handsome guy = Handsome guy("Tough", "handsome", "Thick and thick")
    val test1 = Test(2.0)
    val test2 = Test(2.0, 3)
}

This code is a little long, but the content is very simple, and I will separate it

  1. Class definition:
Class < class name > constructor (parameter 1 / parameter 1, parameter 2 / parameter 2){

}

Kotlin's constructors are divided into primary constructor and secondary constructor. Simple understanding is the main constructor written after the class name The one written in the class is a sub constructor When the main constructor is modified by the visibility modifier, the constructor keyword must be added, otherwise it can be omitted, such as three handsome classes

  1. Only classes decorated by the open keyword can be inherited
  • In Kotlin, inheritance uses colon: as inheritance class or implementation interface
  • Two are the secondary constructors. If the primary constructor is defined, the secondary constructor needs to inherit the primary constructor
  1. Parameter and parameter defined in the class, parameter defined by handsome man
  2. init method When using the main constructor, since there is no method body, some initialization operations can be implemented in the init {} method. This method is executed every time an object is created
  3. Only the sub constructor can overload the construction method
  4. The formal parameter can be called in the method (if val voice: String remove val, the guild will report wrong).
  5. The parent class of all classes in java is Object, and the parent class of all classes in Kotlin is Any
6. empty type

In Kotlin, there are more strict requirements for functions. For example, in Java, you can write such a method:

public String getName() {
        return null;
    }

That's fine, but not in Kotlin

An error will be prompted, meaning that you cannot return an empty string PS: here is the definition of the method in Kotlin:

< visibility modifier > other modifiers > fun method name (parameter 1, parameter 2): < return value type >{

} 

It's not hard to understand. It's basically the same as Java. There's nothing to say What if this method returns to the province and may be empty? You can write as follows:

fun getName(): String? {
    return null
}

String? Indicates that it is a null able string, which can be called as follows:

fun getName(): String? {
    return null
}

fun main(args: Array<String>) {

    val nameB:String? = getName()
    println(nameB?.length)//  
}

nameB? In this way, if the name is not empty, the output length will be printed. Otherwise, null will be printed. In this way, the program will not crash, but there is another situation as follows:

    val value:String ?= "HelloWorld"
    println(value!!.length)

Define value as a nullable type, but I know it is not null. Then we can use value!!, which means that I am sure that this value is not null. Do not report compilation errors to me.

summary

  • Val not null: String = null / / error, cannot be empty
  • val nullable: String? = null / / correct, can be empty
  • notNull.length / / correct. Values that are not empty can be used directly
  • nullable.length / / error, may be empty, cannot get the length directly
  • nullable!!.length / / correct, force nullable to be non null
  • Nullalbe
7. Intelligent type conversion

Here's how:

 if (name != null)
        println(name.length) 
    else 
        return

//Equivalent to:

  val name: String = getName()?: return
  println(name.length) 

If the condition statement determines that the name must not be empty, then the method can be called directly, that is, only String can be converted to String

Java:

class Parent{

}
class Chlid extends Parent{
    public int age=11
}

public void main(){
    Parent parent=new Child()
    ((Chlid)parent).age
}

Methods of subclasses can only be called by strong transformation, but in Kotlin, they are not as follows:

val parentA: Parent = Chlid()
    if (parentA is Chlid) {
        parentA.age
    }

Is keyword, common language judgment. If the judgment is true, parentA is Child does not need forced conversion. The forced conversion is as follows:

    val chlidA: Chlid = parentB as Chlid//crash of non security forced transfer failure
    val chlidB: Chlid? = parentB as? Chlid//Security forced conversion failure is null

Conclusion:

◆ Java Style type conversion

  • val sub: SubClass = parent as SubClass
  • Similar to Java type conversion, throw exception if failure

◆ safety type conversion

  • val sub: SubClass? = parent as? SubClass
  • If the conversion fails, return null without throwing exception

◆ intelligent type conversion

  • If (parent is subclass) parent. < member of subclass >
  • The compiler deduces types as much as possible, away from useless type conversions
  • if(nullable != null) nullable.length
  • Correct! Because we confirm that nullable is not empty
8. interval

As for the concept of interval comparison, it is simple to say the following concepts:

  • Mathematical concepts, ranges
  • Subclass of ClosedRange, IntRange is the most commonly used
  • Basic writing:
    • 0.. 100 means [0, 100]
    • 0 until 100 means [0, 100)
    • i in 0..100 judge whether i is in the interval [0, 100]

Code:

val rangeInt: IntRange = 1..1024//[0,1024]
val range_exclusive: IntRange = 0 until 1024//[0,1024)
val b: Boolean = true

fun main(args: Array<String>) {
    println(rangeInt.contains(50))
    println(rangeInt.contains(1024))
    println(1024 in rangeInt)
    println(range_exclusive.contains(1024))
    println(1024 in range_exclusive)

    for (i in range_exclusive) {
        println(i)
    }
}
9. array

How to use arrays

  • val array: Array = array0f...)

basic operation

  • print array[i] output the ith member
  • Array [i] =, "hello" assigns value to the ith member
  • array.length the length of the array

To avoid unnecessary boxing and unpacking, the basic type of array is customized as follows:

Example:

val arrayInt: IntArray = intArrayOf(1, 3, 5, 7)
val arrayChar: CharArray = charArrayOf('H', 'e', 'l', 'l', 'o')
val arrayString: Array<String> = arrayOf("Chen", "crown", "Greek")
val array secretary: Array<Secretary of municipal Party committee> = arrayOf(Secretary of municipal Party committee("Zhang"), Secretary of municipal Party committee("Plum"), Secretary of municipal Party committee("king"))

fun main(args: Array<String>) {
    println(arrayInt.size)
    for (i in arrayInt) {
        println(i)
    }

    println(arrayChar.joinToString(""))//Connection character
    println(arrayString.joinToString(""))//Connection string
    println(array secretary[1])
    array secretary[1] = Secretary of municipal Party committee("Zhao")
    println(array secretary[1])
    println(arrayInt.slice(1..3))//Indicates subscript slice for slice
}

Last

This year, I spent a month collecting and sorting out a set of knowledge system. If you have an idea to study systematically, you can click Portal , I will give you all my collected and sorted materials to help you advance faster.

Posted by itpvision on Sun, 15 Dec 2019 19:55:39 -0800