Kotlin学习(三):表达式

//java

switch(a){

case 0 : c = 5; break;

case 1 : c = 4; break;

default : c = 20 ;

}

//kotlin

when(a){

0 -> c = 5

1 -> c = 4

else -> c = 20

}

when 多个值相同 可用,间隔 如下所示:

when(a){

0 , 2 -> c = 5

1 -> c = 4

else -> c = 20

}

//也可写为

c = when(a){

0 , 2 -> 5

1 -> 4

else -> 20

}

3.try…catch


try…catch 也是表达式,可直接将变量提取使用

//java

try{

c = a/b;

}catch(Exception e){

e.printStactTrace();

c = 0;

}

//kotlin

c = try{

a/b

}catch(e:Exception){

e.printStactTrace()

0

}

三、kotlin运算符重载与中辍表达式

======================================================================================

1.kotlin运算符重载


运算符operator,kotlin支持运算符重载,但是运算符的范围仅限官方指定的符号:官网路径

用于重载运算符的所有函数都必须使用operator关键字标记。如下简单的demo所示:

// 一个简单的数据类

data class Foo(val x: Int, val y: Int) {

operator fun plus(other: Foo) : Foo = Foo(x + other.x, y + other.y)

}

fun main(args: Array) {

// 使用的时候

val f1 = Foo(10, 20)

val f2 = Foo(30, 40)

// 直接用+运算符代替plus函数,事实上会调用plus函数

println(f1 + f2) // 打印内容为Foo(x=40, y=60)

}

也可以使用扩展函数对运算符进行重载,如下所示:

// 自定义复数运算符 重载运算符

/**

  • @param real 实部

  • @param image 虚部

*/

class Complex(var real: Double, var image: Double) {

override fun toString(): String {

return “real: r e a l i m a g e : real image: realimage:{image}i”

}

}

// 使用扩展方法 进行运算符重载

operator fun Complex.plus(other: Complex): Complex {

return Complex(this.real + other.real, this.image + other.image)

}

operator fun Complex.plus(other: Double): Complex {

return Complex(this.real + other, this.image)

}

operator fun Complex.plus(other: Int): Complex {

return Complex(this.real + other, this.image)

}

operator fun Complex.minus(other: Complex): Complex {

return Complex(this.real - other.real, this.image - other.image)

}

fun main(){

// 运行 自定义复数例子

val complex1 = Complex(3.0, 2.0)

val complex2 = Complex(2.0, 3.0)

//使用

println((complex1 + complex2).toString())

println((complex1 + 1).toString())

println((complex1 + 1.2).toString())

println((complex1 - complex2).toString())

}

除了上述的加减之外,kotlin还支持其他类型的运算符重载,具体可上,官网查看。

Demo:为String实现四则运算

// 为string实现四则运算

// minus 减

operator fun String.minus(right: Any?): String {

val str = right?.toString() ?: “”

return this.replaceFirst(str, “”)

}

// times

operator fun String.times(right: Int): String {

return (1…right).joinToString(“”) { this }

}

// div 除

operator fun String.div(right: Any?): Int {

val str = right?.toString() ?: “”

// windowed 返回给定大小的窗口的快照列表,这些快照沿着给定步骤的字符序列滑动,其中每个快照都是一个字符串。 count 返回为true的个数

return windowed(str.length, 1) {

it == str

}.count { true }

}

fun main() {

val str = “hello world world”

// minus

println(str - “hello”)

// times

println(“*” * 20)

// div

println(str / “l”)

}

2.kotlin中辍表达式 infix


中辍表达式使用infix标记

那什么是中辍表达式呢?

在第一章学习的时候,我们知道Pair是一个对象 包含两个值,frist以及second 。源码如下所示:

public data class Pair<out A, out B>(

public val first: A,

public val second: B

) : Serializable {

/**

  • Returns string representation of the [Pair] including its [first] and [second] values.

*/

public override fun toString(): String = “($first, $second)”

}

如何快速生成Pair呢? 如下所示

val pair1: Pair<Int, Int> = 2 to 3

这个to就是一个中辍表达式,定义源码如下:

public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

仿照上方源码,我们自定义一个中辍表达式,如下:

// 定义中辍表达式

infix fun String.rotate(count: Int): String {

val index = count % this.length

return this.substring(index) + this.substring(0, index)

}

fun main(){

// 使用自定义的中辍表达式

val s = “helloworld” rotate 5

println(s)

}

//运行结果为

worldhello

四、Lambda表达式

==============================================================================

1.kotlin匿名函数


kotlin普通函数以及kotlin匿名函数对比

//一个普通函数

fun func(){

println(“hello”)

}

//一个匿名函数

fun(){

println(“hello”)

}

//匿名函数的引用

val func = fun(){

println(“hello”)

}

//对引用的匿名函数调用

func()

2.匿名函数的类型


kotlin匿名函数的类型与普通函数一致

val func : () -> Unit = fun(){

println(“hello”)

}

3.Lambda表达式的定义,java与kotlin对比


示例如下所示(其中java的实例,指的是从java8开始):

//java

Runnable lambda = () -> {

System.out.println(“hello”);

}

//kotlin

val lambda = {

println(“hello”)

}

lambda表达式的类型

//类型1 入参Int 无返回

val f1 : (Int) -> Unit = {

p:Int ->

println§

}

//类型2 入参Int 返回String

val f2 : (Int) -> String= {

p:Int ->

println§

“hello”

}

//类型3 入参Int,String 返回String

val f3 : (Int,String) -> String= {

p:Int,s:String ->

println(“ p p ps”)

“hello”

}

lambda表达式省略参数的写法,如果只有一个参数,可使用it代替

val f : Function1<Int,Unit> = {

println(it)

}

总结

最后

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!
也去过华为、OPPO等大厂,18年进入阿里一直到现在。**

深知大多数初中级Android工程师,想要提升技能,往往是自己摸索成长,自己不成体系的自学效果低效漫长且无助

因此我收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。

[外链图片转存中…(img-VgeR2P7O-1715680588997)]

[外链图片转存中…(img-VAzdDQoo-1715680588999)]

[外链图片转存中…(img-Guzfz7cd-1715680589000)]

[外链图片转存中…(img-IVtx21bf-1715680589001)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点!不论你是刚入门Android开发的新手,还是希望在技术上不断提升的资深开发者,这些资料都将为你打开新的学习之门

如果你觉得这些内容对你有帮助,需要这份全套学习资料的朋友可以戳我获取!!

由于文件比较大,这里只是将部分目录截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且会持续更新!

  • 18
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值