Kotlin一之内置类型

目录

一、基本类型

二、数组


一、基本类型

整型默认类型是Int,浮点数默认类型是double。

数值型的Float需要在数字后面写上大写的L,不可以是小写的l

Kotlin 复制代码
// val c: Long = 4l // 编译就报错,只能用大写的L
val c: Long = 4L

不支持隐式转换,可以直接用数字赋值。比如一个函数参数为Double 的函数只能接收 Double 类型,不能接收 Float、Int 或者其他数字类型。Long类型也不能接受Int类型。

Kotlin 复制代码
    val bInt = 3
    var b: Long = 3 // 可以
    b = 4
//    b = bInt // 编译就报错,不支持隐式转换
    b = bInt.toLong()
    var doubleNumber1: Double = 6.0
    // 报错 The floating-point literal does not conform to the expected type Double
//    doubleNumber1 = 3.0f // 报错,因为3.0f,相当于明确指出了是Float类型,Float类型不能给Double类型赋值

== 表示值比较,===表示引用比较,看是否是同一个对象。

Kotlin 复制代码
fun stringFunction() {
    val str = "Hello" // 常量池
    val str2 = "Hello"
    val hello = String("Hello".toCharArray()) // 创建了对象
    val hello2 = String("Hello".toCharArray())
    println("str hello value equal? ${str==hello}") // 比较值 true
    println("str is hello? ${str===hello}") // 比较引用 false
    println("str str2 value equal? ${str==str2}") // 比较值 true
    println("hello is hello2? ${hello===hello2}") // 比较引用 false
}

二、数组

Kotlin java
整型 IntArray int[]
整型-包装类型 Array<Int> Integer[]
字符型 CharArray char[]
字符型-包装类型 Array<Char> Character[]
字符串类型 Array<String> String[]
[java VS Kotlin 对照]

长度不可以变,可以通过foreach,迭代器,for(.. in ..)遍历。

查看是否包含某个元素,可以用indexOf(),若存在返回第一次出现的下标,否则返回-1。源码其实也是用for(.. in .. )实现的。

相关推荐
火柴就是我4 小时前
让我们实现一个更好看的内部阴影按钮
android·flutter
FunnySaltyFish7 小时前
什么?Compose 把 GapBuffer 换成了 LinkBuffer?
算法·kotlin·android jetpack
砖厂小工10 小时前
用 GLM + OpenClaw 打造你的 AI PR Review Agent — 让龙虾帮你审代码
android·github
张拭心11 小时前
春节后,有些公司明确要求 AI 经验了
android·前端·人工智能
张拭心11 小时前
Android 17 来了!新特性介绍与适配建议
android·前端
Kapaseker13 小时前
Compose 进阶—巧用 GraphicsLayer
android·kotlin
黄林晴14 小时前
Android17 为什么重写 MessageQueue
android
阿巴斯甜1 天前
Android 报错:Zip file '/Users/lyy/develop/repoAndroidLapp/l-app-android-ble/app/bu
android
Kapaseker1 天前
实战 Compose 中的 IntrinsicSize
android·kotlin
xq95272 天前
Andorid Google 登录接入文档
android