
44
|
第
2
章
将此功能与多行字符串结合使用,示例 2-27 给出了可以很好地改变原始 joke 的 Kotlin
版本。
示例 2-27:实现关于二进制的 joke(笑 话)
val joke = """
Actually, there are ${3.toString(3)} kinds of people
Those who know binary, those who don't,
And those who didn't realize this is actually a ternary joke
""".trimIndent()
println(joke)
这段代码的输出如下所示:
Actually, there are 10 kinds of people
Those who know binary, those who don't,
And those who didn't realize this is actually a ternary joke
2.6
数幂
问题
如何计算数幂?但请注意,Kotlin 没有预先定义的幂运算符。
解决方案
定义一个中缀函数,该中缀函数委托给已经添加到 Int 与 Long 中的 Kotlin 扩展函数
pow。
讨论
像 Java 一样,Kotlin 没有内置的幂运算符。Java 至少在 java.lang.Math 类中包含静
态 pow 函数,其签名如下:
public static double Math.pow(double a, double b) ...