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

相关推荐
硬件学长森哥2 小时前
Android影像基础--cameraAPI2核心流程
android·计算机视觉
honder试试6 小时前
焊接自动化测试平台图像处理分析-模型训练推理
开发语言·python
^Rocky6 小时前
JavaScript性能优化实战
开发语言·javascript·性能优化
ponnylv6 小时前
深入剖析Spring Boot启动流程
java·开发语言·spring boot·spring
萧邀人6 小时前
第一课、Cocos Creator 3.8 安装与配置
开发语言
前行的小黑炭7 小时前
Android 协程的使用:结合一个环境噪音检查功能的例子来玩玩
android·java·kotlin
阿华的代码王国7 小时前
【Android】内外部存储的读写
android·内外存储的读写
Jayden_Ruan7 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
不吃鱼的羊7 小时前
启动文件Startup_vle.c
c语言·开发语言
VBA63378 小时前
VBA之Word应用第四章第二节:段落集合Paragraphs对象(二)
开发语言