【Android、 kotlin】kotlin学习笔记

本文介绍了Kotlin编程语言的基础概念,包括变量的val和var区分、标准输出方法、基本数据类型、控制流(如if、range和when)、for循环、数组与集合操作、函数定义(含lambda表达式和高阶函数),以及类的使用。
摘要由CSDN通过智能技术生成

基本语法

fun main(){
    val a=2
    var b = "Hello"
    println("$ (a - 1} $b Kotlin!")

}

Variables

只赋值一次用val read-only variables with val

赋值多次用var mutable variables with var

Standard output

printin() and print() functions

String templates

Template expressions start with $

Evaluate a niece of code with {}

基本数据类型basic types

声明变量Declare Variables

val pi : Double =3.14
var p : Int
p = pi.tolnt()

需要强制类型转换Explicit number conversions

99802211d7634aa694ad8d16ec6263b8.jpg

控制流control flow

if语句

max = if (a > b) a else b
val a = 4
val b = 5
val max : Int
if (a > b) {
	max = a
}
else {
	max = b
}
println("max = $max")

 range函数

Ranges - create a range to use ..

1..4 equivalent to 1, 2, 3, 4

1..<4 equivalent to 1, 2, 3

4 downTo 1 equivalent to 4, 3, 2, 1

1..5 step 2 equivalent to 1, 3, 5

when函数

Use when when you have a conditional expression with multiple branches

val temp = 20
val description = when(temp) {
    	0 -> "zero"
    	in 1..10 -> "a bit cold"
    	in 11..<20 -> "warm"
    	else -> "hot"             
}
print(description)

for循环

The for loop iterates through anything that provides an iterator. 

for (i in 1..3) {
    println(i)
}
for (i in array.indices) {
    println(array[i])
}
for ((index, value) in array.withIndex()) {
    println("elem at $index is $value")
}

Array

val simpleArray = arrayOf(1, 2, 3)
val intArray : Array<Int> = arrayOf(4, 5, 6)
simpleArray[0] = 10
val exampleArray = IntArray(3)

Collections: List, Set, Map 

函数functions

Basic function

fun sum(a: Int, b: Int): Int {
    return a + b
}

Function body can be expression

只有一条表达式语句

fun sum(a: Int, b: Int) = a + b

Function without return value

fun printSum(a: Int, b: Int): Unit {
    println("sum of $a and $b is ${a + b}")
}

Lambda expressions

如果lambda表达式有多个语句,最后一个语句是返回值

fun main() {

var upperCaseString : (String) -> String

upperCaseString = { string: String -> string.uppercase() }

println(upperCaseString("hello"))

}

高阶函数higher-order function

A higher-order function is a function that takes functions as parameters, or returns a function.

包含函数或者函数返回值的函数是高阶函数

fun main() {

val result = operateTwoNumber(1, 2, { a: Int, b: Int -> a + b })#最后一个变量是函数,可以它放在括号外面

}

fun operateTwoNumber(x: Int, y: Int, op: (Int, Int) -> Int): Int {

return op(x, y)

}

`it`

主要用于函数类型中,当函数只有一个参数时,`it`用来表示这个参数对象。

类classes

  • 17
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

岩塘

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值