当前位置:网站首页>Android 开发用 Kotlin 编程语言一 基本数据类型
Android 开发用 Kotlin 编程语言一 基本数据类型
2022-08-05 10:52:00 【AaVictory.】
一、简介
Kotlin: 是世界各地的 Android 开发者广泛使用的一种编程语言
二、变量声明
1、Kotlin 使用两个不同的关键字
- val :用于值从不更改的变量。使用 val 声明的变量无法重新赋值。
- var :用于值可以更改的变量。
2、举例说明
//num是一个 Int 类型的变量,初始赋值为 10
var num: Int = 10
//可以将 num的值从 10 更改为 15
num=15
Int 是一种表示整数的类型,是可以用 Kotlin 表示的众多数值类型之一。与其他语言类似,您还可以使用 Byte、Short、Long、Float 和 Double,具体取决于您的数值数据。
- 假设有一个名为 name 的 String。如果希望确保 name的值始终为“Kotlin”,则可以使用 val 关键字声明 name:
val name: String = "Kotlin"
通过这些关键字,您可以明确指出哪些变量的值可以更改。请根据需要加以利用。如果引用的变量必须可重新赋值,则将其声明为 var。否则,请使用 val。
三、类型推断
val name= "Kotlin"
由于 “Kotlin” 的值为 String 类型,因此编译器推断 name 也为 String。请注意,Kotlin 是一种静态类型的语言。这意味着,类型将在编译时解析且从不改变。
利用 Kotlin 的类型推断,既能确保代码简洁,又能确保类型安全
四、Null 安全
在某些语言中,可以声明引用类型变量而不明确提供初始值。在这类情况下,变量通常包含 null 值。默认情况下,Kotlin 变量不能持有 null 值。这意味着以下代码段无效:
val name:String= null
- 要使变量持有 null 值,它必须是可为 null 类型。可以在变量类型后面加上 ? 后缀,将变量指定为可为 null,如以下示例所示:
val name:String? = null
- 指定 String? 类型后,可以为 name 赋予 String 值或 null。
必须小心处理可为 null 的变量,否则可能会出现可怕的 NullPointerException。例如,在 Java 中,如果尝试对 null 值调用方法,程序会发生崩溃。
边栏推荐
- Opencv算术操作
- Import Excel/CSV from Sub Grid within Dynamics 365
- 发现C语言的乐趣
- 字节一面:TCP 和 UDP 可以使用同一个端口吗?
- PostgreSQL 2022 Report: Rising popularity, open source, reliability and scaling key
- FPGA: Basic Getting Started Button Controlling LED Lights
- 19.3 restart the Oracle environment
- SMB + SMB2: Accessing shares return an error after prolonged idle period
- 大佬们 我是新手,我根据文档用flinksql 写个简单的用户访问量的count 但是执行一次就结束
- FPGA:基础入门按键控制LED灯
猜你喜欢

FPGA:开发环境Vivado的使用

Use KUSTO query statement (KQL) to query LOG on Azure Data Explorer Database

abc262-D(dp)

API 网关简述

The host computer develops C# language: simulates the STC serial port assistant to receive the data sent by the microcontroller

负载均衡应用场景

The founder of the DFINITY Foundation talks about the ups and downs of the bear market, and where should DeFi projects go?

Google启动通用图像嵌入挑战赛

结合“xPlus”探讨软件架构的创新与变革

【深度学习】mmclassification mmcls 实战多标签分类任务教程,分类任务
随机推荐
STM32入门开发:编写XPT2046电阻触摸屏驱动(模拟SPI)
MMDetection实战:MMDetection训练与测试
Latex如何控制表格的宽度和高度
Three methods for extracting facial features
gradle尚硅谷笔记
使用Windbg过程中两个使用细节分享
【 temperature warning program DE development 】 event driven model instance
SkiaSharp 之 WPF 自绘 投篮小游戏(案例版)
HDD杭州站•ArkUI让开发更灵活
This notebook of concurrent programming knowledge points strongly recommended by Ali will be a breakthrough for you to get an offer from a big factory
CenOS MySQL入门及安装
Chapter 4: activiti RuntimeService settings get and get process variables, and the difference from taskService, set process variables when starting and completing tasks [easy to understand]
第四章:activiti流程中,变量的传递和获取流程变量 ,设置和获取多个流程变量,设置和获取局部流程变量「建议收藏」
012年通过修补_sss_提高扩散模型效率
012_SSS_ Improving Diffusion Model Efficiency Through Patching
19.3 restart the Oracle environment
工程设备在线监测管理系统自动预警功能
PostgreSQL 2022 报告:流行度上涨,开源、可靠性和扩展是关键
数据可视化(二)
Data Middle Office Construction (10): Data Security Management