fun main(args: Array<String>) {
println(convert2Int("ab"))
printMultiply("2","3")
printMultiply("a","3")
}
//返回值可能是Int,或是null,故Int加问号代表可能为Int亦可能为null
fun convert2Int(str: String): Int? {
try {
return str.toInt()
} catch (ex: NumberFormatException) {
return null
}
}
//字符串转换成整数相乘
fun printMultiply(a: String,b: String){
var a1 = convert2Int(a)//返回Int?类型的a1变量
var a2 = convert2Int(b)
if (null != a1 && null != a2) {
println(a1 * a2)
}else{
println("It doesn't work!")
}
}
输出:
null
6
It doesn't work!