kotlin - 如何使用默认值组合两个函数?
问题描述
我想将这两个功能结合起来,但我很难做到。有人可以帮我吗?
fun String?.pluralize(count: Int): String? {
return if (count != 1) {
this + 's'
} else {
this
}
}
fun String?.pluralize(count: Int, plural: String?): String? {
return if (count != 1) {
plural ?: this + 's'
} else {
this
}
}
解决方案
获得所需结果并处理null
输入情况的正确方法String
应该如下:
fun String?.pluralize(count: Int, plural: String? = null): String? = when {
count == 1 || this == null -> this
else -> plural ?: "${this}s"
}
推荐阅读
- java - Error: incompatible types:byte cannot be converted to Boolean (illegal start of expression)
- database - MongoDB做多对多关系的方式
- java - 单击加载本地 HTML 页面的导航抽屉上的字符串/链接
- ruby - 使用正则表达式获取 Nokogiri 节点
- c# - 用前缀为 =(等号)的双引号替换包含日期和时间的字符串
- php - 使用特定术语进行 wordpress 循环
- java - JButton上的Java ImageIcon重复图像
- python - UDP 使用以太网电缆点对点通信不起作用?
- c# - Fody 在参考项目上编织?
- python - 将 ndarray 转换为 Base64