- 课程名称:一课掌握Kotlin 突破开发语言瓶颈
- 章节名称:
- 复习
- 讲师姓名:bennyhuo
- 时间:2022-08-19 23:39
课程内容
-
用写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()) }
学习心得
对于函数是一等公民的要求还不是很理解