上一篇关于kotlin内联函数的文章,讲了let函数,需要去学习的可以看上一篇文章,链接如下:
kotlin 之几个常见的内联函数(一)_水很清的博客-CSDN博客
讲完了let,这篇文章将with,还是按照上一篇的讲解结构篇幅来,现在开始
一、函数结构为
public inline fun with(receiver: T, block: T.() -> R): R = receiver.block()
它表示T类型在调用with后将变为R类型。
二、一般使用结构:
- with(object){
- //todo
- }
三、with 函数底层的inline扩展函数+lambda结构
- @kotlin.internal.InlineOnly
- public inline fun
with(receiver: T, block: T.() -> R): R = receiver.block()
四、函数结构分析
with函数它不是以扩展的形式存在的。它是将某对象作为函数的参数,在函数块内可以通过 this 指代该对象。同时this也可以省略,也就是在函数快里面可以直接使用对象的属性活方法。返回值为函数块的最后一行或指定return表达式。
五、举个栗子
可以看出with函数是接收了两个参数,分别为T类型的对象receiver和一个lambda函数块,所以with函数最原始样子如下:
- val result = with(user, {
- println("my name is $name, I am $age years old, my phone number is $phoneNum")
- 1000
- })
-
- //代码分析:with函数返回值是最后一行代码,也就是result=1000
由于with函数最后一个参数是一个函数,可以把函数提到圆括号的外部,最终with函数的调用形式如下:
- val result = with(user) {
- println("my name is $name, I am $age years old, my phone number is $phoneNum")
- 1000
- }
-
- //代码分析:with函数返回值是最后一行代码,也就是result=1000
看起来更加的简洁。
六、kotlin 与 java的代码对比
- //kotlin
- fun main(args: Array
) { - val user = User("Kotlin", 1, "1111111")
-
- val result = with(user) {
- println("my name is $name, I am $age years old, my phone number is $phoneNum")
- 1000
- }
- println("result: $result")
- }
-
- //java
- public static final void main(@NotNull String[] args) {
- Intrinsics.checkParameterIsNotNull(args, "args");
- User user = new User("Kotlin", 1, "1111111");
- String var4 = "my name is " + user.getName() + ", I am " + user.getAge() + " years old, my phone number is " + user.getPhoneNum();
- System.out.println(var4);
- int result = 1000;
- String var3 = "result: " + result;
- System.out.println(var3);
- }
七、使用场景
适用于调用同一个类的多个方法时,可以省去类名重复,直接调用类的方法即可,经常用于Android中RecyclerView中onBinderViewHolder中,数据model的属性映射到UI上。
比如下面列子:
- //java代码
- @Override
- public void onBindViewHolder(ViewHolder holder, int position) {
-
- ArticleSnippet item = getItem(position);
- if (item == null) {
- return;
- }
- holder.tvNewsTitle.setText(StringUtils.trimToEmpty(item.titleEn));
- holder.tvNewsSummary.setText(StringUtils.trimToEmpty(item.summary));
- String gradeInfo = "难度:" + item.gradeInfo;
- String wordCount = "单词数:" + item.length;
- String reviewNum = "读后感:" + item.numReviews;
- String extraInfo = gradeInfo + " | " + wordCount + " | " + reviewNum;
- holder.tvExtraInfo.setText(extraInfo);
- ...
- }
-
- //kotlin代码
- override fun onBindViewHolder(holder: ViewHolder, position: Int){
- val item = getItem(position)?: return
- with(item){
- holder.tvNewsTitle.text = StringUtils.trimToEmpty(titleEn)
- holder.tvNewsSummary.text = StringUtils.trimToEmpty(summary)
- holder.tvExtraInf.text = "难度:$gradeInfo | 单词数:$length | 读后感: $numReviews"
- ...
- }
- }
可以看到,使用对象属性的时候,直接就是属性名,而不是对象+属性名。这在较复杂的情况下,会体现出更加的简洁。
以上就是with的全部内容,下一篇将run。that's all