欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

Kotlin学习-基础知识点

发布时间:2025/7/14 编程问答 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Kotlin学习-基础知识点 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

一:基础要点

//常量定义 val
val arg_a1: Int = 1  
//变量定义var
var arg_a2 = 5  // 系统自动推断变量类型为Int

备注:kotlin 定义变量必须给定初始值,如延迟初始值,需要特殊声明!

空对象处理
//可null对象声明

//类型后面加?表示可为空var agrs_t: String? = null //抛出空指针异常val v1 = agrs_t!!.toInt() //不做处理返回 null //the safe call operator, written ?.val v2 = agrs_t?.toLong() //age为空时返回-1, 非空正常执行val v3 = agrs_t?.toInt() ?: -1

 

//显示判断处理val l: Int = if (b != null) b.length else -1val b: String? = "Kotlin"if (b != null && b.length > 0) {print("String of length ${b.length}")} else {print("Empty string")}//安全处理符处理 //the safe call operator, written ?.val lt = b?.length ?: -1//为空为-1val files = File("Test").listFiles()println(files?.size ?:"empty")

 

 

类型判断及转化

//类型判断,如果为String类型,则自动转为String
if (obj is String) {
    print(obj.length)
}
// 非此类型判断,same as !(obj is String)
if (obj !is String) {
    print("Not a String")
}

//可null类型转化
val x: String? = y as String?
//非null转化
//null cannot be cast to String as this type is not nullable,
val x2: String = y as String

 

equels与引用比较:

两个对象内容比较(Java中的equels)==两个等号代表

两个引用比较使用===三个等号代表

Equality checks: a == b    ,!==
Referential equality: a === b

 

this关键字引用含义

class A { // implicit label @Ainner class B { // implicit label @Bfun Int.foo() { // implicit label @fooval a = this@A // A's thisval b = this@B // B's thisval c = this // foo()'s receiver, an Intval c1 = this@foo // foo()'s receiver, an Intval funLit = lambda@ fun String.() {val d = this // funLit's receiver}val funLit2 = { s: String ->// foo()'s receiver, since enclosing lambda expression// doesn't have any receiverval d1 = this}}} }

 说明:

1,this默认不加标签,如在类的成员内,标识当前类对象,在成员函数或扩展函数内部则this代表的是接受者类型对象(如变量c,c1代表作用对象Int)

2,this加上@对应类名称代表指定类对象引用,如a,b

 

 

函数定义

//返回值函数
fun sum(a: Int, b: Int): Int {
    return a+b
}

//无返回值
fun getHello(){
        //......
 }

//不定参数定义函数
fun varsFor(vararg v:Int){//变长参数 vararg
    for(vt in v){
        print(vt)
    }
}

 //函数返回可null类型
fun getStringLength(obj: Any): Int? {
    // `obj` 的类型会被自动转换为 `String`
    if (obj is String && obj.length > 0)
        return obj.length
    return null // 这里的obj仍然是Any类型
}

 

//函数作为参数传递

fun testHandleMethodParams(){val strSample = "handle filter"val tvalue = transformResult (strSample){//函数作为参数getParams(strSample)}}fun getParams(str1: String): Int = str1.length/*** arg0 为实参* p1 为形参,内部无法引用* ->函数返回值*/fun <T, R> transformResult(args:T,transform: (T) -> R): R {return transform(args)}

 

/*** 此方法接收一个无参数的函数并且无返回,Unit表示无返回*/private fun getResults(method: () -> Unit) {method()}

 

 

数组类型
//默认值初始化 [1,2,3]
 val a = arrayOf(1, 2, 3)
//表达式初始化
 val b = Array(3, { i -> (i * 2) })
//指定元素个数,空元素数组初始化
 var attr = arrayOfNulls<String>(5)
 attr[1] = "11"
 attr[2] = "22"

数组遍历
fun vForArray(array: Array<Int>){
    //withIndex 函数 index value 一对同时遍历
    for ((index, value) in array.withIndex()) {
        println("the element at $index is $value")
    }
    //索引遍历
    for (i in array.indices) {
        print(array[i])
    }
    //值遍历
    for(v in array){
        print("$v \t")
    }
}

 

集合类型 分为可变和不可变集合
1,集合类型包含三种类型:它们分别是:List、Set、Map
2,三种集合类型分别对应MutableList<E>、MutableSet<E>、MutableMap<K,V>接口

    //List 创建
    val list1 = listOf(1,2,"3",true) // 不定类型创建
    val list2 = listOf<String>("1","2","3")  // 确定元素类型
    val list3 = listOf(a)// 使用数组创建
    //备注:List一旦创建不可修改,add set remove不可操作
    
    //mutableList 创建
    val mutaList1 = mutableListOf<String>("1","2","3")
    val mutaList2 = mutableListOf(a)
    mutaList1.add("11")
    mutaList1.removeAt(2)
    mutaList1.set(0,"mm")

 

集合常用函数

 

fun listOperate(){val items = listOf(1, 2, 3, 4)items.first() //== 1items.last() //== 4val subItems = items.filter { it % 2 == 0 } // returns [2, 4]var sub2 = items.slice(1..3)var sub3 =items.filterNot { it>100 }//高阶函数//遍历listitems.forEach{ // it= it*2+1print(it)}items.forEachIndexed { index, value -> if (value > 8) println("value of index $index is $value") }//T->R 集合中的元素通过某个方法转换后的结果存到一个集合val list11 = items.map { (it - 2+1).toLong() }val list111 = items.mapIndexed { index, it -> if(index>5) 10 * it }//合并两个集合 // items.flatMap { listOf(it, it + 1) }// map:遍历每一个元素 // flatMap:遍历每一个元素,并铺平(展开内部嵌套结构)元素var list_map = listOf(listOf(10,20),listOf(30,40),listOf(50,60))var mapList = list_map.map{ element -> element.toString() }var flatMapList = list_map.flatMap{ element -> element.asIterable() } // map [[10, 20], [30, 40], [50, 60]] // flatmap [10, 20, 30, 40, 50, 60]// filter all 符合条件elementval list12 = items.filter { mypre(it) }//filter 到第一个不符合条件元素返回,后面不再过滤val list13 = items.takeWhile { (it%2!=0) }//提取前3个元素val list14 = items.take(3)//提取后3个val list15 = items.takeLast(3)//去除重复元素var list16 = items.distinct()//指定key过滤条件var list17 = items.distinctBy { it*101+100 } // list1.fold(5,operation = )//匹配交集元素var list18 = items.intersect(listOf<Int>(2,3,4))//匹配两个集合内所以不同元素,差集合var list19 = items.union(listOf<Int>(2,3,4))//返回匹配条件元素var list21 = items.any { (it in 10..20) }var list22 = items.count { it >20 }//初始值,累计计算处理var list23 = items.fold(10) { total, next -> total + next }var list24 =items.reduce { total, next -> total - next }var sumFilterResult : Int = 0items.filter { it < 7 }.forEach { sumFilterResult += it }val rwList = mutableListOf(1, 2, 3)// 去除null元素rwList.requireNoNulls() //returns [1, 2, 3]//检测list内有符合条件元素if (rwList.none { it > 6 }) println("No items above 6") // prints "No items above 6"//第一个元素,或为空对象val item = rwList.firstOrNull()}
fun mypre(t:Int): Boolean{
    return t%2==0
}

 

转载于:https://www.cnblogs.com/happyxiaoyu02/p/9953689.html

总结

以上是生活随笔为你收集整理的Kotlin学习-基础知识点的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。