if
语句,这些分支可以用 when
表达式替换。
示例:
fun checkIdentifier(id: String) {
fun Char.isIdentifierStart() = this in 'A'..'z'
fun Char.isIdentifierPart() = isIdentifierStart() || this in '0'..'9'
if (id.isEmpty()) {
print("Identifier is empty")
} else if (!id.first().isIdentifierStart()) {
print("Identifier should start with a letter")
} else if (!id.subSequence(1, id.length).all(Char::isIdentifierPart)) {
print("Identifier should contain only letters and numbers")
}
}
建议通过快速修复将 if
表达式转换为 when
表达式:
fun checkIdentifier(id: String) {
fun Char.isIdentifierStart() = this in 'A'..'z'
fun Char.isIdentifierPart() = isIdentifierStart() || this in '0'..'9'
when {
id.isEmpty() -> {
print("Identifier is empty")
}
!id.first().isIdentifierStart() -> {
print("Identifier should start with a letter")
}
!id.subSequence(1, id.length).all(Char::isIdentifierPart) -> {
print("Identifier should contain only letters and numbers")
}
}
}