当前位置:网站首页>Basic use of kotlin

Basic use of kotlin

2022-07-04 19:42:00 AdleyTales

fun main() {
    
    println("hello world, Hello Kotlin ~")

    val result = sum(12, 5)
    println(result) // 17

    val result2 = sum2(12, 5)
    println(result2) // 17

    val result3 = sum2(12, 5)
    println(result3) // 17

    varsFunc("aaaa", "bbbb", "cccc", "dddd", " Ying pengliang ")

    println("******------******------******------******------******------******------")

    //  Define constants and variables  val Same as java Of final
    val firstname = "adley"
    val lastname = "tales"

    //  String template 
    val str = "My name is $firstname $lastname !"
    println(str)

    // NULL Inspection mechanism 
    //  Air safety   Add... After the field !! image Java Throw an empty exception , Another field is followed by ? Do not process the return value is  null  perhaps  ?:  Short judgment processing 

    //  Type followed by ? Can be empty 
    var name: String? = "adley"
    name = null
    println(name)

    //  Throws a null pointer exception 
    // var age = name!!.toInt()

    //  Return... Without processing  null
    val age2 =name?.toInt()
    println(age2) // null

    val ages3 = age2?.toInt() ?: -1 //  If it's empty , Then for -1
    println(ages3) // -1

    println(name is String) // false
    println(str is String) // true

    //  Section 
    for (i in 1..5) {
    
        println(i)
    }

    for (i in 1..5 step 2) {
    
        println(i)
    }
}

//  Basic usage 
//  Package declaration : package com.adleytales.demo

//  Function definition 
fun sum(x: Int, y: Int): Int {
    
    return x + y
}

//  function 
fun sum2(x: Int, y: Int): Int = x + y

//  function  lambda
val sum3: (Int, Int) -> Int = {
     x, y -> x + y }

//  Variable length parameters  vararg
fun varsFunc(vararg str: String) {
    
    for (s in str) {
    
        println(s)
    }
}
原网站

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