kotlin 运算符_Kotlin属性,数据类型,运算符
kotlin 运算符
In this tutorial, we’ll be digging deep into the basic fundamental blocks of Kotlin, namely Kotlin Properties and Data Types. If you aren’t aware of Kotlin, it’s recommended to go through the introductory post, before proceeding ahead.
在本教程中,我们将深入研究Kotlin的基本基本知识,即Kotlin属性和数据类型。 如果您不了解Kotlin,建议先进行介绍 ,然后再继续。
Kotlin房地产 (Kotlin Properties)
Properties are undoubtedly the most important element in any programming language. They’re indispensable in any codebase. Let’s look at how they’re defined in Kotlin and what makes them stand out from Java.
Open up IntelliJ and create a new Kotlin project followed by creating a Kotlin file.
Every kotlin property declaration begins with the keyword var
or val
. val
is used when the variable is immutable i.e. read-only. You can only set the value once. Following is the syntax defined for int variables in kotlin programming.
属性无疑是任何编程语言中最重要的元素。 它们在任何代码库中都是必不可少的。 让我们看看它们在Kotlin中的定义方式以及使它们在Java中脱颖而出的原因。
打开IntelliJ并创建一个新的Kotlin项目,然后创建一个Kotlin文件。
每个kotlin属性声明都以关键字var
或val
开头。 当变量是不可变的(即只读)时使用val
。 您只能设置一次该值。 以下是kotlin编程中为int变量定义的语法。
var x: Int = 0
val y: Int = 1
x = 2
y = 0 //This isn't possible.var a: Int
a = 0
val b: Int
b = 1
b = 2 //Not possibleval z: Double = 1 // Not possible. We need to pass an Int here.
As it is evident in the above code, the type of the variable is specified after the colon.
Note: Kotlin doesn’t require a semicolon at the end of each statement.
从上面的代码中可以明显看出,变量的类型在冒号之后指定。
注意 :Kotlin在每个语句的末尾不需要分号。
属性类型和Sytnax (Properties Types And Sytnax)
Following is the complete syntax of a Kotlin Property.
以下是Kotlin属性的完整语法。
var <propertyName>[: <PropertyType>] [= <property_initializer>][<getter>][<setter>]
Getters and Setters are optional. Setters aren’t possible for a val
property, since it is immutable.
Classes in Kotlin can have properties.
If a getter or setter isn’t defined, the default ones are used.
Getter和Setter是可选的。 val
属性无法使用setter,因为它是不可变的。
Kotlin中的类可以具有属性。
如果未定义getter或setter,则使用默认值。
吸气剂和二传手 (Getters And Setters)
Currently, there are a few variants of getters and setters in Kotlin. Let’s look at each of them separately
by creating a Kotlin class as shown below.
当前,在Kotlin中有一些getter和setter的变体。 让我们分别看一下
通过创建如下所示的Kotlin类。
class A {var name: Stringset(value) = println(value)get() = this.tutorialvar tutorial : String = "Kotlin"set(value) {println("Old value was $field New Value is $value")}get() {return "${field.length}"}
}fun main(args: Array<String>) {var a = A()println(a.name)a.name = "Kotlin Getters And Setters"println(a.tutorial)a.tutorial = "Kotlin Properties"}//Following is printed in the log.
//6
//Kotlin Getters And Setters
//6
//Old value was Kotlin New Value is Kotlin Properties
In the above code, we use the setters to print the old and new values after the new one is set.
We haven’t initialized the property name
. Hence it takes the value of the getter. The getter of the name
property invokes the property tutorial
. Hence the initial value of name
is fetched from the getter of tutorial
field
holds the backing value of a property.
在上面的代码中,我们使用设置器在设置新值后打印旧值和新值。
我们尚未初始化属性name
。 因此,它需要获取方法的价值。 name
属性的获取程序将调用属性tutorial
。 因此, name
的初始值是从本tutorial
的getter获取的
field
保存属性的支持值。
We can further specifier a modifier on the setters and getters too.
我们还可以在setter和getter上进一步指定修饰符。
var name: String
private set(value) = println(value)
get() = this.tutorial
The visibility modifier on a get must be the same as the property.
Now the above property cannot be set from any function outside the class.
获取上的可见性修饰符必须与属性相同。
现在,无法从类之外的任何函数设置以上属性。
const vs val (const vs val)
const
is like val
, except that they are compile-time constants.
const are allowed only as a top-level or member of an object.
const
类似于val
,只是它们是编译时常量。
const只允许作为对象的顶级或成员。
const val x = "Hello, Kotlin" //would compileval y = printFunction() //works.
const val z = printFunction() //won't work. const works as a compile time constant only.fun printFunction()
{
println("Hello, Kotlin")
}class A {
const val x = "Hello, Kotlin" //won't compile. const can be only used at top level or in an object.}
const
cannot be used with var.
const
不能与var一起使用。
懒惰vs Lateinit (lazy vs lateinit)
lazy
is lazy initialization. Your val
property won’t be initialized until you use it for the first time in your code. Henceforth, the same value would be used. The value is present in the lazy()
function which takes the value in the form of a lambda.
lazy
是惰性初始化。 除非您在代码中首次使用val
属性,否则不会对其进行初始化。 此后,将使用相同的值。 该值存在于lazy()
函数中,该函数采用lambda形式表示该值。
val x: Int by lazy { 10 }
lateinit
modifier is used with var
properties and is used to initialize the var
property at a later stage. Normally, Kotlin compiler requires you to specify a value to the property during initialization. With the help of lateinit
you can delay it.
lateinit
修饰符与var
属性一起使用,并在以后阶段用于初始化var
属性。 通常,Kotlin编译器要求您在初始化期间为属性指定一个值。 借助lateinit
您可以延迟它。
fun main(args: Array<String>) {var a = A()a.x = "Hello Kotlin"
}class A {lateinit var x: String
}
lateinit
cannot be used with val
.
lateinit
cannot be used with primitive types.
lateinit var
can be initialized from anywhere where the object is created.
lateinit
不能与val
一起使用。
lateinit
不能与基本类型一起使用。
lateinit var
可以从创建对象的任何位置进行初始化。
Kotlin使用类型推断 (Kotlin Uses Type Inference)
The Kotlin compiler can figure out the type of the property based on the value you specify. Being a statically typed language, the type is inferred at compile-time and not runtime. Type inference saves us from specifying the type of every variable. Thus, our codebase would look less verbose. Following snippet uses type inference to determine the property types.
Kotlin编译器可以根据您指定的值来确定属性的类型。 作为一种静态类型的语言,类型是在编译时而不是运行时推断的。 类型推断使我们不必指定每个变量的类型。 因此,我们的代码库看起来不太冗长。 以下代码段使用类型推断来确定属性类型。
var x= 0 //Kotlin infers the type as Int
val y = 1.5 // Kotlin infers the type as Double
x = "Hello" //Won't work. Can't set a String value to an Int.val a = 1.5
a = 2.5 //Won't work. val is immutable
Important note: You either need to define the type or set the value to a property. Else a compile-time error would occur.
重要说明 :您需要定义类型或将值设置为属性。 否则会发生编译时错误。
var a //won't compile. You need to specify either type or value.var x= 1
val y: Double//val variable can be assigned only one value in a single block.
if(x>0)
{y = 1.5
}
else{y = 2.5
}
Kotlin数据类型 (Kotlin Data Types)
Following are the basic kotlin data types that can be assigned to a variable.
以下是可分配给变量的基本kotlin数据类型。
- Numbers号码
- Characters性格
- Boolean布尔型
- Arrays数组
- Strings弦乐
号码 (Numbers)
In Kotlin, any of the following can be Numbers. Every type has a certain bit width that the compiler allocates.
在Kotlin中,下列任何一个都可以是数字。 每个类型都有编译器分配的特定位宽。
- Double – 64双– 64
- Float – 32浮点数– 32
- Long – 64长– 64
- Int – 32整数– 32
- Short – 16短– 16
- Byte – 8字节– 8
The Kotlin compiler can’t infer the types Short and Byte. We need to define them as shown below
Kotlin编译器无法推断Short和Byte类型。 我们需要如下定义它们
var a: Int = 0
var b: Short = 10
var c: Byte = 20
Similar to Java, for a Long and Float type you can append the letter L and F(or f) respectively to the variable value.
与Java类似,对于Long和Float类型,可以将字母L和F(或f)分别附加到变量值之后。
val l = 23L
var f = 1.56F
var d = 1.55
var e = 1.55e10 //Alternative form to define a double value.
Smaller types cannot be implicitly converted to larger ones in Kotlin. The following would throw an error.
在Kotlin中,较小的类型不能隐式转换为较大的类型。 以下将引发错误。
var b: Short = 10
val i: Int = b //Error
Kotlin provides us with methods to explicitly convert a smaller type to a larger one.
Kotlin为我们提供了将较小的类型显式转换为较大的类型的方法。
var b: Short = 10
val i: Int = b.toInt() //Works
Kotlin provides helper functions for conversion between each type : toByte()
, toInt()
, toLong()
, toFloat()
, toDouble()
, toChar()
, toShort()
, toString()
(To convert the string to a number if valid!).
Kotlin提供辅助功能对于每种类型之间的转换: toByte()
toInt()
toLong()
toFloat()
toDouble()
toChar()
toShort()
toString()
将字符串转换为数字,如果有效!)。
We can add underscores in number literals to improve readability.
我们可以在数字文字中添加下划线以提高可读性。
val tenMillion = 10_000_000 // reads 10000000
val creditCardNumber = 1234_5678_9012_3456L // reads 1234567890123456
性格 (Characters)
Character types are denoted by Char
and the value is specified in single quotes.
字符类型用Char
表示,值用单引号引起来。
var c: Char = 'A'
//or using the shorthand form
var c = 'A'var d: Char = 'AB' //this won't work. Only one character allowed.
Furthermore, a character can be assigned a Unicode value too as shown below.
此外,如下所示,也可以为字符分配Unicode值。
val character : Char = '\u0041'
Unlike Java, Characters in Kotlin can’t be set using ASCI values. The following won’t compile
与Java不同,不能使用ASCI值设置Kotlin中的字符。 以下内容无法编译
var c:Char = 65 //won't work
The reason for the above anomaly is put on type inference. However, we can add an int to a char or convert it to an int to get the ASCII.
出现上述异常的原因是类型推断。 但是,我们可以将int添加到char或将其转换为int以获取ASCII。
var c:Char = 'A'
var newChar = c + 1 // B
布尔型 (Boolean)
The type Boolean represents booleans, and has two values: true and false.
Built-in operations on booleans include
布尔类型表示布尔值,并具有两个值: true和false 。
布尔值的内置操作包括
- || – lazy disjunction (OR)|| –延迟析取(OR)
- && – lazy conjunction(AND)&& –懒惰连词(AND)
- ! – negation(NOT)! –否定(NOT)
var characterA = 'C'
var characterB = 'E'
var characterC = 'A'if(characterA>characterB || characterA>characterC)
{println("CharacterA isn't the smallest") //this gets printed
}if(characterA>characterB && characterA>characterC)
{println("characterA isn't the smallest") //this gets printed
}
else{println("characterA is definitely smaller than characterB") //this gets printed
}
Note: We’ll be looking at Strings and Array types at length in a later tutorial.
注意 :在后面的教程中,我们将详细介绍Strings和Array类型。
Kotlin运算符 (Kotlin Operators)
Following are the major operators used in Kotlin.
以下是Kotlin中使用的主要运算符。
- Equality Operators:
a==b
anda!=b
var equalityChecker = (characterA == characterC) println(equalityChecker) //prints trueequalityChecker = (characterA != characterC) println(equalityChecker) //prints false
等号运算符 :
a==b
和a!=b
- Comparison operators:
a < b
,a > b
,a <= b
,a >= b
比较运算符 :a < b
,a > b
,a <= b
,a >= b
- Range instantiation and range checks:
a..b
,x in a..b
(checks if x is in the range of a to b),x !in a..b
(checks if x is not in the range of a to b)范围实例化和范围检查 :a..b
,a..b
中的x in a..b
(检查x是否在a到b的范围内),x !in a..b
(检查x是否不在a到b的范围内) b) - Increment and decrement operators :
++
and--
. Post and pre-increment/decrement both exist. Also, we can use the functioninc()
anddec()
too(Both are used as post increment/decrement)var a: Int = 0 var c = a++ // 0 println(a) //prints 1 a.inc() println(a) //prints 1 c = --a // 1
Post increment/decrement stores the current value and then increments/decrements.
Pre increment/decrement increments/decrements and then stores the value.递增和递减运算符 :
++
和--
。 后和前增加/减少都存在。 另外,我们也可以使用函数inc()
和dec()
(两者都用作后期增量/减量)增量递增/递减后存储当前值,然后递增/递减。
预先递增/递减递增/递减,然后存储该值。 - Bitwise Operators: Unlike Java, Bitwise operators in Kotlin aren’t special characters. Instead, they are named forms of those characters.
shl(bits) – signed shift left (Java’s <<)
shr(bits) – signed shift right (Java’s >>)
ushr(bits) – unsigned shift right (Java’s >>>)
and(bits) – bitwise and
or(bits) – bitwise or
xor(bits) – bitwise xor
inv() – bitwise complementvar a = 10 var b = 20 var sum = a or b println(sum) //prints 30sum = a and b println(sum) //prints 0
按位运算符 :与Java不同,Kotlin中的按位运算符不是特殊字符。 而是将它们命名为这些字符的形式。
shl(bits)–有符号左移(Java的<<)
shr(bits)–带符号的右移(Java >>)
ushr(bits)–无符号右移(Java >>>)
和(位)–按位和
或(位)–按位或
xor(bits)–按位异或
inv()–按位补码
Note: Ternary operators are NOT supported in Kotlin.
注意 :Kotlin不支持三元运算符。
This brings an end to this tutorial in Kotlin.
这样就结束了Kotlin中的本教程。
References: Kotlin Docs
参考: Kotlin Docs
翻译自: https://www.journaldev.com/17311/kotlin-properties-data-types-operators
kotlin 运算符
kotlin 运算符_Kotlin属性,数据类型,运算符相关推荐
- c语言程序设计课件第二章,c语言程序设计课件张元国 ISBN9787566300386 PPT第二章数据类型 运算符与表达式...
1.第2章 数据类型.运算符与表达式,语言的数据类型 常量与变量 运算符与表达式 不同类型数据间的转换,2.1语言的数据类型,数据是计算机程序处理的所有信息的总称,数值.字符.文本等都是数据,在各种程 ...
- 前端JavaScript(1) --Javascript简介,第一个JavaScript代码,数据类型,运算符,数据类型转换,流程控制,百度换肤,显示隐藏...
一.Javascript简介 Web前端有三层: HTML:从语义的角度,描述页面结构 CSS:从审美的角度,描述样式(美化页面) JavaScript:从交互的角度,描述行为(提升用户体验) Jav ...
- JavaScript(一)(数据类型+运算符)
JavaScript(一)(数据类型+运算符) 文章目录 JavaScript(一)(数据类型+运算符) 一.数据类型 1. 什么是 JavaScript 语言? 1.1 定义 1.2 实验环境 2. ...
- c语言程序计算p q真值表,C语言程序设计第2章数据类型﹒运算符和表达式.ppt
C语言程序设计第2章数据类型﹒运算符和表达式 教学目标 掌握C语言标识符的组成 理解C语言的基本数据类型 掌握变量定义的方法 掌握常用的运算符的使用 掌握混合运算的数据转换方法 2.1 C语言的数据类 ...
- 数据类型,运算符和表达式03 - 零基础入门学习C语言04
第二章:数据类型,运算符和表达式03 让编程改变世界 Change the world by program 字符型数据 字符型数据包括字符常量和字符变量 字符常量: 是用单引号括起来的一个字符. 例 ...
- 二进制补码求值用c语言,C语言程序设计第2章数据类型.运算符与表达式.ppt
C语言程序设计第2章数据类型.运算符与表达式 教学目标 掌握C语言标识符的组成 理解C语言的基本数据类型 掌握变量定义的方法 掌握常用的运算符的使用 掌握混合运算的数据转换方法 2.1 C语言的数据类 ...
- 3月6日 输入与输出 数据类型 运算符
Main函数: static void Main(string [] args) { } 程序代码需要写在Main函数的花括号内. 一.输入与输出: string s=Console.Readline ...
- 数据类型,运算符和表达式02 - 零基础入门学习C语言03
第二章:数据类型,运算符和表达式02 让编程改变世界 Change the world by program 整型变量 整型变量的分类(注意:这里占多少个字节跟系统和编译器规定有关!可以在编译器上自己 ...
- Python精通-运算符与基本数据类型(一)
导语 之前的分享中简单的说了运算符合基本的数据类型,这里继续来分享运算符和基本数据类型.并且使用PyCharm进行开发 文章目录 回顾 补充 运算符 引入新的数据类型 布尔值(bool) 判断条件 ...
最新文章
- 转载:Linux查看设置系统时区
- linux下socket上限,[100分]高分求关于linux socket上限解决方案
- NYOJ 358 取石子(五)
- 2018-2019-2 20165114《网络对抗技术》Exp4 恶意代码分析
- 图解DOM中关于对象范围的属性
- BeetleX服务网关流量控制
- 卷积神经网络CNN介绍:结构框架,源码理解【转】
- php pdo mysql 预处理_php -- PDO预处理
- Linux之du命令
- switch语句小练习
- 面具更新自定义_面具Magisk如何从稳定版切换到测试版,面具版本切换教程
- keras学习率下降策略
- 计算机辅助教育课件有哪些类型,多媒体计算机辅助教学 (2).ppt
- 百度数据挖掘实习生面试经验
- 轴功率测试软件,船用轴功率检测仪 在线轴功率测量装置
- 代理沙特SASO贸促会认证
- 【2023秋招】9月京东校招题目
- 硬盘分区表丢失、修复大事记--分区表修复利器testdisk
- 企业物联卡如何充值,几百张卡能同时充值吗?【物联卡中心】
- 在VS2017中使用Xlslib对Excel进行操作