概述
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.
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中脱颖而出的原因。
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 possible
val 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.
Getter和Setter是可选的。 val
属性无法使用setter,因为它是不可变的。
吸气剂和二传手 (Getters And Setters)
Currently, there are a few variants of getters and setters in Kotlin. Let’s look at each of them separately
当前,在Kotlin中有一些getter和setter的变体。 让我们分别看一下
class A {
var name: String
set(value) = println(value)
get() = this.tutorial
var 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.
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.
获取上的可见性修饰符必须与属性相同。
const vs val (const vs val)
const
is like val
, except that they are compile-time constants.
const
类似于val
,只是它们是编译时常量。
const val x = "Hello, Kotlin" //would compile
val 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.
布尔类型表示布尔值,并具有两个值: 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 true equalityChecker = (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.
递增和递减运算符 :++
和--
。 后和前增加/减少都存在。 另外,我们也可以使用函数inc()
和dec()
(两者都用作后期增量/减量)增量递增/递减后存储当前值,然后递增/递减。
- Bitwise Operators: Unlike Java, Bitwise operators in Kotlin aren’t special characters. Instead, they are named forms of those characters.
var a = 10 var b = 20 var sum = a or b println(sum) //prints 30 sum = a and b println(sum) //prints 0
按位运算符 :与Java不同,Kotlin中的按位运算符不是特殊字符。 而是将它们命名为这些字符的形式。
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属性,数据类型,运算符的全部内容,希望文章能够帮你解决kotlin 运算符_Kotlin属性,数据类型,运算符所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复