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 .. )实现的。

相关推荐
火车叼位27 分钟前
Android Studio与命令行Gradle表现不一致问题分析
android
前行的小黑炭2 小时前
【Android】 Context使用不当,存在内存泄漏,语言不生效等等
android·kotlin·app
前行的小黑炭3 小时前
【Android】CoordinatorLayout详解;实现一个交互动画的效果(上滑隐藏,下滑出现);附例子
android·kotlin·app
用户20187928316715 小时前
Android黑夜白天模式切换原理分析
android
芦半山16 小时前
「幽灵调用」背后的真相:一个隐藏多年的Android原生Bug
android
卡尔特斯16 小时前
Android Kotlin 项目代理配置【详细步骤(可选)】
android·java·kotlin
ace望世界16 小时前
安卓的ViewModel
android
ace望世界16 小时前
kotlin的委托
android
CYRUS_STUDIO19 小时前
一文搞懂 Frida Stalker:对抗 OLLVM 的算法还原利器
android·逆向·llvm
zcychong19 小时前
ArrayMap、SparseArray和HashMap有什么区别?该如何选择?
android·面试