【Kotlin】扩展函数 ② ( 扩展属性 | 为可空类型定义扩展函数 | 使用 infix 关键字修饰单个参数扩展函数的简略写法 )





一、扩展属性



上一篇博客 【Kotlin】扩展函数 ( 扩展函数简介 | 为 Any 超类定义扩展函数 | private 私有扩展函数 | 泛型扩展函数 | 标准函数 let 函数是泛型扩展函数 ) 中 , 介绍了给 现有类 定义 扩展函数 , 此外还可以 给现有类定义 扩展属性 ;


为现有类定义 扩展属性 语法格式为 :

val 现有类类名.扩展属性名: 扩展属性类型
	get() = {
    
    } 

var 现有类类名.扩展属性名: 扩展属性类型
	get() = {
    
    } 
	set() = {
    
    } 
  • 扩展属性 不能 进行初始化 , 必须在 getter 函数中进行初始化 ;
  • val 只读类型变量 扩展属性 必须提供 getter 函数 ;
  • var 可变类型变量 扩展属性 必须提供 getter 和 setter 函数 ;

代码示例 : 在该代码中 , 为 String 类型定义了 扩展属性 extAttribute , 由于是 val 只读变量 , 因此必须在其 setter 函数 中进行初始化变量 , 并且 不能提供 setter 函数 ;

val String.extAttribute: Int
    get() {
    
    
        return 10
    }

fun String.addStr(str: String): String {
    
    
    println("this = $this, string = $str")
    return this + str
}

fun main() {
    
    
    println("123".addStr("abc"))
    println("123".extAttribute)
}

执行结果 :

this = 123, string = abc
123abc
10




二、可空类扩展



之前讲的定义扩展函数 , 扩展属性 , 都是为 非空类型 定义的 ,

如果要为 可空类型 定义扩展函数 , 则需要在 扩展函数 中 处理时 , 要多考虑一层 接收者 this 为空 的 情况 ;


注意下面的调用细节 :

  • 如果定义的 扩展函数 是 为 非空类型定义的 , 可空类型变量 想要调用该 扩展函数 , 在调用时使用 " ?. " 进行调用即可 ;
	可空类型实例对象?.非空类型扩展函数
  • 如果定义的 扩展函数 是为 可空类型定义的 , 可空类型变量 想要调用该 扩展函数 , 在调用时直接使用 " . " 进行调用即可 ;
	可空类型实例对象.可空类型扩展函数

代码示例 :

fun String?.addStr(str: String): String {
    
    
    if (this == null) {
    
    
        println("this = $this, string = $str, 接收者为空")
        return str
    } else {
    
    
        println("this = $this, string = $str, 接收者不为空")
        return this + str
    }
}

fun main() {
    
    
    var nullString: String? = null

    println("123".addStr("abc"))
    println(nullString.addStr("abc"))
}

执行结果 :

this = 123, string = abc, 接收者不为空
123abc
this = null, string = abc, 接收者为空
abc




三、使用 infix 关键字修饰单个参数扩展函数的简略写法



如果 扩展函数 只有 一个参数 , 并且在 扩展函数 定义时 使用了 infix 关键字修饰 , 在调用该扩展函数时 , 可以省略 接收者与函数之间的点参数列表的括号 ;


调用 使用 infix 关键字修饰 单个参数扩展函数 :

接收者 函数名 函数参数 

也可以使用 传统方式调用 :

接收者.函数名(函数参数)

Map 中 创建 的 Pair 实例对象to 函数 , 就是 被 infix 修饰的 泛型扩展函数 , 最终产生的是 Pair 实例对象 ;

/**
 * 从this和[that]创建类型为[Pair]的元组。
 *
 * 这对于创建噪音更少的[Map]字面量很有用,例如:
 * @sample samples.collections.Maps.Instantiation.mapFromPairs
 */
public infix fun <A, B> A.to(that: B): Pair<A, B> = Pair(this, that)

代码示例 :

infix fun String.addStr(str: String): String {
    
    
    return this + str
}

fun main() {
    
    
    println("123".addStr("abc"))

    // 简略写法如下
    println("123" addStr "abc")
}

执行结果 :

123abc
123abc

猜你喜欢

转载自blog.csdn.net/han1202012/article/details/128754528
今日推荐