前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Kotlin 扩展函数与属性 实例代码

Kotlin 扩展函数与属性 实例代码

作者头像
一个会写诗的程序员
发布2018-11-21 18:04:42
4970
发布2018-11-21 18:04:42
举报

Java

代码语言:javascript
复制
package com.easykotlin.lec03_kotlin_extensions;

import java.util.List;

public class CollectionUtils {
    public static void swap(List<Integer> list, int src, int target) {
        int temp = list.get(src);
        list.set(src, list.get(target));
        list.set(target, temp);
    }
}


package com.easykotlin.lec03_kotlin_extensions;

import java.util.ArrayList;
import java.util.List;

public class JavaDemo {
    public static void main(String[] args) {
        test();
    }

    public static void test() {
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(7);
        CollectionUtils.swap(list, 0, list.size() - 1);
        System.out.println(list);

        String str = "This Java Programming Language";
        String newStr = StringUtils.convertSpace2UnderScore(str);
        System.out.println(newStr);
    }
}

Kotlin

代码语言:javascript
复制
fun MutableList<Int>.swap(src: Int, target: Int) {  // 函数的接收者 this
    val temp = this[src]
    this[src] = this[target]
    this[target] = temp
}

// 扩展属性
val MutableList<Int>.sum: Int
    get() {
        var sum = 0
        this.forEach { sum += it }
        return sum
    }

package com.easykotlin.lec03_kotlin_extensions

fun main(args: Array<String>) {
    val array = mutableListOf(1, 2, 3, 4, 5, 6, 7)
    array.swap(0, array.size - 1)
    array.forEach { print("$it,") }
}

第2个例子: Java

代码语言:javascript
复制
package com.easykotlin.lec03_kotlin_extensions;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class StringUtils {
    public static String convertSpace2UnderScore(String src) {
        return src.replaceAll(" ", "_");
    }

    public static String exe(String cmd) {
        try {
            Process p = Runtime.getRuntime().exec(cmd);
            InputStream ins = p.getInputStream();
            InputStream es = p.getErrorStream();

            String inputLines = "";
            BufferedReader brIns = new BufferedReader(new InputStreamReader(ins));
            String line;

            do {
                line = brIns.readLine();
                inputLines += line + "\n";
            } while (line != null);

            String errorLines = "";
            BufferedReader brErr = new BufferedReader(new InputStreamReader(es));
            String errLine;
            do {
                errLine = brErr.readLine();
                errorLines += errLine + "\n";
            } while (errLine != null);

            return inputLines + "\n" + errorLines;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

StringUtils.exe("ls -R");

Kotlin

代码语言:javascript
复制
package com.easykotlin.lec03_kotlin_extensions


object StringUtilsKotlin {
    fun convertSpace2UnderScore(src: String): String {
        return src.replace(" ".toRegex(), "_")
    }
}


fun String.convertSpace2UnderScore(): String {
    return this.replace(" ", "_")
}

infix fun String.convert(s: String): String {
    return this.replace(" ", s)
}

fun String.exe(): String {
    val cmd = this
    val p = Runtime.getRuntime().exec(cmd)
    val ins = p.inputStream
    val es = p.errorStream

    var inputLines = ""
    val brIns = ins.bufferedReader()
    var line: String?

    do {
        line = brIns.readLine()
        inputLines += "$line\n"
    } while (line != null)

    var errorLines = ""
    val brErr = es.bufferedReader()
    var errLine: String?
    do {
        errLine = brErr.readLine()
        errorLines += "$errLine\n"
    } while (errLine != null)

    return "$inputLines\n$errorLines"
}
代码语言:javascript
复制
    val str = "This Kotlin Programming Language"
    println(StringUtilsKotlin.convertSpace2UnderScore(str))
    // Kotlin 仅仅能够做到这些? Of Course not ... Let's see extension functions :)
    println(str.convertSpace2UnderScore())
    println(str convert "$")

    println("ls -R".exe())
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.11.20 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档