LeetCode 算法题 BAT 字节跳动 拼多多 美团 京东大厂面试题集锦

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

2018-11-20  本文已影响42人  光剑书架上的书

Java

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

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

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

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"
}
    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())
上一篇 下一篇

猜你喜欢

热点阅读