[Kotlin] Compare Functional Programming in Java and Kotlin

Java way:

package com.rsk.java;

import java.util.function.Function;

public class FPExample {
    public static Function<String, String> toSentenceCase = x -> x.substring(0, 1).toUpperCase() + x.substring(1);

    public static String applySomeFunctionToAString(String inputString, Function<String, String> myFunction) {
        return myFunction.apply(inputString);
    }

    public static void main(String args[]) {
        String result = applySomeFunctionToAString("hello", toSentenceCase);
        System.out.println(result);
    }
}

 

Kotlin:

package com.rsk

fun toSentenceCase(x: String) = x[0].toUpperCase() + x.substring(1)

fun applySomeFunctionToAString(inputString: String, myFunction: (String) -> String): String {
    return myFunction(inputString);
}

fun main(args: Array<String>) {
    val result = applySomeFunctionToAString("hello", ::toSentenceCase)
    val result2 = applySomeFunctionToAString("hello") {it.toUpperCase()}
    println(result)
    println(result2)
}

 

上一篇:快速排序算法


下一篇:java代码练习 work119