Kotlin基本语法练习第二章

本文深入探讨Kotlin语言特性,包括函数声明、动态参数、流程控制、类声明、作用域函数及委托属性的使用。通过实例讲解延迟属性、可观察属性的概念,并演示了lambda表达式、标签控制流、默认参数及异常处理的实践。同时,文章还介绍了作用域函数的多种应用,如let、run、with、apply和also。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

kotlin基本语法练习第二章

函数声明和动态参数
try cath用法
break 和continue流程控制关键字的使用、标签的声明和使用
类声明和类成员函数调用
作用域函数的使用
委托属性的声明和使用

package com.wzx.jetpartpro

import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import kotlin.reflect.KProperty


/*
* create by WuZhouXing
* on 2020/5/9 18:06
*
*/

/*
*  @author  wuzhouxing  2020/5/9 18:08
*  @description 委托属性
*  延迟属性(lazy properties): 其值只在首次访问时计算;
*  可观察属性(observable properties): 监听器会收到有关此属性变更的通知;
*  把多个属性储存在一个映射(map)中,而不是每个存在单独的字段中。
*/

class Example {
    var p: String by Delegate()
}

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "$thisRef,thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name}' in $thisRef")
    }
}

val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}

data class Person(var name:String, var age:Int, var city:String){
    fun moveTo(newCity:String){
        city=newCity
    }
    fun incrementAge(){
        age++;
    }
}




/*
 *  @author  wuzhouxing  2020/5/12 16:04
 *  @description 函数的默认参数 ,类似python 动态传参,没有java中强制传参的形式
 *   def readfile(test="fets",cha=1): 动态类型编程语言,不需要类型声明
 */
fun foo(a: Int = 0, b: String = "") {

    /*
    *  @author  wuzhouxing  2020/5/12 16:11
    *  @description 检测元素是否在集合中
    */
    val emaillist = listOf<String>("One", "Two", "Three", "Four")
    if ("One" in emaillist) {
        println("obj contains")
    }

    /*
*  @author  wuzhouxing  2020/5/12 16:19
*  @description 返回和挑战,kotlin中标签的使用
*/
//在kotlin中任何表达式都可以用标签(label)来标记,标签的格式为标识符后跟@符号
    loop@ for (i in 1..100) {
        println("sample1=$i")
        for (j in 1..100){
            if(i<=j)
                println("sample3 break i=$i,j=$j")
                break@loop
        }
    }


    //break 跳出内层循环
     for (i in 1..100) {
        println("sample2=$i")
         loop@for (j in 1..100){
            if(i<=j)
                println("sample2 break i=$i,j=$j")
            break@loop
        }
    }

    loop@ for (i in 1..100) {
        println("sample3=$i")
        for (j in 1..100){
            if(i<=j)
                println("sample3 continue print i=$i,j=$j")
            continue@loop
        }
    }
}

fun foo1(){
    /*
    *  @author  wuzhouxing  2020/5/12 16:39
    *  @description lambda这个内联函数的我也不习惯,敲惯了冗余代码的人,觉得太花哨
    */
    //lambda 表达式
    listOf(1,2,3,4,5).forEach{
        if(it==3) return
        println(it)
    }
}

fun count(){
    val strArr=listOf("try", "catch","test")
    val length=strArr.size>3?:throw ArithmeticException("List size error")
}

/*
*  @author  wuzhouxing  2020/5/12 16:54
*  @description try catch表达式
*/
fun test(){
 val result=try{
     count()
 }catch (e:java.lang.ArithmeticException){
     throw IllegalStateException(e)
 }
}




fun main() {
    println(lazyValue)
    println(lazyValue)
//    foo()
//    foo1()
    test()

    /*
    *  @author  wuzhouxing  2020/5/12 17:02
    *  @description 使用可以为空的布尔值
    */
    val b:Boolean?=true
    if(b==true){
       println("b is true")
    }else{
        println("b is false or null")
    }

    val temp:Boolean?=null
    if(temp==true){
        println("temp is true")
    }else{
        println("temp is false or null")
    }


    /*
    *  @author  wuzhouxing  2020/5/12 17:26
    *  @description Scope Function 全局作用域函数 有五个这样得函数: let, run, with, apply, and also
    *
    */

    //also 上下文对象 可以作为参数it,传入obj的值
    val numbers= mutableListOf("one","two","three")  //字符串集合对象
    numbers.also { println("The list elements before adding new one: $it") }
            .add("four")

    //let 方法体,obj作为it参数传入,可以直接调用obj桉树
     val alice:Person= Person("Alice",20,"Amsterdam")
     alice.let {
                 println(it)
                 it.moveTo("London")
                 it.incrementAge()
                 println(it)
             }

    //let 方法体里面调用函数处理it也就是str
//    val str:String?="Hello"
    val str:String?=null
    val length=str?.let {
        println("let() called on $it")
        processNonNullString(it)
        it.length
    }
    println("length is $length")


    /*
    *  @author  wuzhouxing  2020/5/12 18:17
    *  @description Scope Function run
    */
    //网络请求
    val service=MultiportService("https://example.kotlinlang.org", 80)
    val result=service.run {
        port=8080
        query(prepareRequest()+" to port $port")
    }

    val letResult=service.let {
        it.port=8080
        it.query(it.prepareRequest()+"to port ${it.port}")
    }
    println(result)
    println(letResult)

}

class MultiportService(var url:String,var port:Int){
    fun prepareRequest():String="Default request"
    fun query(request:String):String="Result for query '$request'"
}

fun processNonNullString(str:String){

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值