当前位置:网站首页>Kotlin variable

Kotlin variable

2022-07-05 12:42:00 Curious rookie

  One 、 Variable definitions


/*
 keyword       Variable type 
 ↓          ↓           */
var price: Int = 100;   /*
     ↑            ↑
    Variable name          A variable's value    */

  In most cases , Variable types can be derived , It can be omitted ; Semicolons at the end are generally omitted ;

  Two 、 The type of variable

 

package com.example.demo

fun main() {
    //     value type 
    val int = 1
    val long = 1234567L
    val double = 13.14
    val float = 13.14F
    val hexadecimal = 0xAF
    val binary = 0b01010101
    //    toByte()、toShort()、toInt()、toLong()、toFloat()、toDouble()、toChar() Type conversion .
    val j = int.toLong();
    //     Boolean type 
    val flag1 = true
    val flag2 = false
    println(flag1 && flag2)

    //     character 
    val c: Char = 'A'

    //     character string 
    val s = "Hello Kotlin!"
    val name = "Kotlin"
    print("Hello $name!") //Hello Kotlin!

    val array = arrayOf("Java", "Kotlin")
    print("Hello ${array.get(1)}!") //Hello Kotlin!


    val s2 = """
        When our string has a complex format 
        The original string is very convenient 
        Because it can do what you see is what you get . """

    print(s2)

    //     Array 

    val arrayInt = arrayOf(1, 2, 3)
    val arrayString = arrayOf("apple", "pear")
    println(arrayInt.size) //3


}

3、 ... and 、 Air safety


val i: Double = null //  Compiler error 

Kotlin Developers are forced to define variables , Specifies whether this variable can be null. For possible null The variable of , We need to make a statement , Add a question mark after the variable type “?”


var i: Double = 1.0
var j: Double? = null

i = j  //  Compiler error 
j = i  //  Compile and pass 

原网站

版权声明
本文为[Curious rookie]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/186/202207051212050368.html