Kotlin_扩展函数与运算符重载

文章介绍了Kotlin语言中的扩展函数概念,展示了如何为String类添加一个计算字母数量的lettersCount()函数。此外,还讲解了运算符重载,通过Money类的例子演示了如何自定义加法操作。同时,文章提到了Kotlin的ainb语法糖以及一个随机生成字符串长度的times()函数,并给出了getRandomLengthString()函数的示例。
摘要由CSDN通过智能技术生成

扩展函数

扩展函数指的是在修改某个类的源码的情况下, 先该类添加新的函数

  1. 向哪个类添加扩展函数, 就定义一个同名的Kotlin文件, 方便查找
  2. 扩展函数可以定义在类中, 不一定要创建新文件, 但是最好将它定义成顶层方法, 这样可以让扩展函数拥有全局的访问域
fun String.lettersCount(): Int {
    var count = 0
    for (char in this) {
        if (char.isLetter()) {
            count++
        }
    }
    return count
}

fun main()
{
    val count = "ABC123xyz!@#".lettersCount()
    println(count)
}

运算符重载

Money对象

class Money(val value: Int) {
    operator fun plus(money: Money): Money {
        val sum = value + money.value
        return Money(sum)
    }
    operator fun plus(newValue: Int): Money {
        val sum = value + newValue
        return Money(sum)
    }
}

fun main()
{
    val money1 = Money(5)
    val money2 = Money(10)
    val money3 = money1 + money2
    val money4 = money3 + 20
    println(money4.value)
}

a in b语法糖

if ("hello".contains("he")) {
}
// 等价于
if ("he" in "hello") {
}

随机生成字符串长度的函数

//operator fun String.times(n: Int): String {
//    val builder = StringBuilder()
//    repeat(n) {
//        builder.append(this)
//    }
//    return builder.toString()
//}
operator fun String.times(n: Int) = repeat(n)

fun getRandomLengthString(str: String) = str * (1..20).random() 

fun main()
{
    val str = "abc" * 3
    println(str)

    println(getRandomLengthString("abc"))
}

参考

郭霖. 《第一行代码 Android 第3版》

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Y_cen

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

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

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

打赏作者

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

抵扣说明:

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

余额充值