用写Java的方式来写一个Kotlin四则运算小程序,直接上代码
fun main(vararg args: String) { if (args.size < 3) { return showHelp() } val operators = mapOf( "+" to ::plus, "-" to ::minus, "*" to ::times, "/" to ::divide ) val op = args[1]; val opFunc = operators[op] ?: return showHelp() println("Input: ${args.contentToString()}") println("Input: ${args.joinToString(" ")}") try { println("Output: ${opFunc.invoke(args[0].toInt(), args[2].toInt())}") } catch (e: Exception) { println("Invalid arguments.") showHelp() } } fun plus(arg0: Int, arg1: Int): Int { return arg0 + arg1 } fun minus(arg0: Int, arg1: Int): Int { return arg0 - arg1 } fun times(arg0: Int, arg1: Int): Int { return arg0 * arg1 } fun divide(arg0: Int, arg1: Int): Int { return arg0 / arg1 } fun showHelp() { println(""" Simple Calculator: Input: 3 * 4 Output: 12 """.trimIndent()) }
对于函数是一等公民的要求还不是很理解