美文网首页
[日更][07]-Kotlin

[日更][07]-Kotlin

作者: 代码多哥 | 来源:发表于2023-08-16 10:57 被阅读0次

因为时间很短,所以内容不是很复杂,写一个有价值的小知识,主要是为了保持每日学习和写作的习惯,大作还是会写到相关的主题里面,尽量做到周更。敬请关注本人的主要作品集:

一路向下之AOSP研究

为了能够最大限度的保证文章的质量,日更主要采用翻译的方法来完成。本系列将主要翻译Kotlin官网的内容。具体的地址

https://kotlinlang.org/docs/home.html

六 集合-List

按添加项目的顺序列出存储项目,并允许重复项目。
要创建只读列表(list),请使用listOf()函数。
要创建可变列表(MutableList),请使用mutableListOf()函数。
创建列表时,Kotlin可以根据函数的参数去推断存储的项目的类型。要显式声明类型,请在列表声明后添加尖括号内的类型,例如:

// Read only list
val readOnlyShapes = listOf("triangle", "square", "circle")
println(readOnlyShapes)
// [triangle, square, circle]

// Mutable list with explicit type declaration
val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
println(shapes)
// [triangle, square, circle]

为了防止不必要的修改,您可以通过将可变列表分配给只读列表来获得可变列表的只读视图:

val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
val shapesLocked: List<String> = shapes

这也叫叫做casting.

对列表进行排序,以便访问列表中的项目,请使用索引访问运算符 [ ]:

val readOnlyShapes = listOf("triangle", "square", "circle")
println("The first item in the list is: ${readOnlyShapes[0]}")
// The first item in the list is: triangle

要获取列表中的第一项或最后一项,请分别使用.first()和.last()函数:

val readOnlyShapes = listOf("triangle", "square", "circle")
println("The first item in the list is: ${readOnlyShapes.first()}")
// The first item in the list is: triangle

.first()和.last() 函数是扩展函数的示例。要在对象上调用扩展函数,请在对象后面写上函数名并附加句点。
有关扩展函数的更多信息,请参阅扩展函数。再本指导文档中,你只需要知道如何称呼他们。

要获取列表中的项数,请使用.count() 函数:

val readOnlyShapes = listOf("triangle", "square", "circle")
println("This list has ${readOnlyShapes.count()} items")
// This list has 3 items

要检查项目是否在列表中,请使用in运算符:

val readOnlyShapes = listOf("triangle", "square", "circle")
println("circle" in readOnlyShapes)
// true

要在可变列表中添加或删除项,请分别使用.add()和.remove()函数:

val shapes: MutableList<String> = mutableListOf("triangle", "square", "circle")
// Add "pentagon" to the list
shapes.add("pentagon") 
println(shapes)  
// [triangle, square, circle, pentagon]

// Remove the first "pentagon" from the list
shapes.remove("pentagon") 
println(shapes)  
// [triangle, square, circle]

译者注释:

  • kotlin 是区分只读和可变类型,只有可变的集合才具有add或者remove等修改操作
  • kotlin的[] 是一个操作符重载函数,它相当于是get(index)或者set(index,obj)方法。
  • koltin的List继承自kotlin.collections.Collection,与java的List没有关系,只不过再JVM平台下,它的实现是基于JAVA的ArrayList,因此在JAVA平台上他们是同一的,但是再其他平台就不同了,因为其他平台根本就没有java的ArrayList
import java.util.ArrayList as JArrayList
...
public fun  test() {
        var jList = JArrayList<String>()
        jList.add("jstring")
        var kList = arrayListOf("kstring")
        var jList2: JArrayList<String> = kList
        var kList2: ArrayList<String> = jList
        jList2.forEach {
            println(it)
        }
        kList2.forEach {
            println(it)
        }
    }

我们可以看到在java工程里,Java的ArrayList和Kotlin的ArrayList是可以相互赋值。但是使用Java的ArrayList将失去跨平台的能力,因此如果有Kotlin的类型时,应使用Kotlin的类型,从而具有跨平台的能力。

相关文章

网友评论

      本文标题:[日更][07]-Kotlin

      本文链接:https://www.haomeiwen.com/subject/jexcmdtx.html