文章目录
一、复合符号
1、=== !== (三等)
== 是比较值是否相等
=== 是比较对象的地址是否相等
2、!! (断言非空操作符)
!! 比如 var s = foo!! 如果foo不为null 就取出值,如果foo为null 就抛出异常
3、?(当前是否对象可以为空)
4、?. (安全调用符)
代码:
if (foo != null) {
return foo.bar()
} else {
return null
}
5、?:(类似java的判断)
6、is
val str = "helloWorld"
System.out.println("========")
println(str is String)//输出:true
System.out.println("========")
输出信息:
I/System.out: ========
true
========
7、!is
val x = 10
System.out.println("========")
println(x !is Int)//输出:false
System.out.println("========")
输出信息:
I/System.out: ========
false
========
8、as (类型不安全的转换符),转换成功就转换成功,转换失败会报错
private var view1: View? = null
private var view2: View? = null
private var view3: View? = null
private var mListView1: ListView? = null
private var mListView2: ListView? = null
private var mListView3: ListView? = null
...
view1 = inflater.inflate(R.layout.pager_number, null)
view2 = inflater.inflate(R.layout.pager_number, null)
view3 = inflater.inflate(R.layout.pager_number, null)
//as转换成功就转换成功
mListView1 = view1!!.findViewById<View>(R.id.listview) as ListView
mListView2 = view2!!.findViewById<View>(R.id.listview) as ListView
mListView3 = view3!!.findViewById<View>(R.id.listview) as ListView
9、as? (类型安全转换符),as?比as安全一点,转换成功就转换成功,转换失败会返回null
1.输出非null
var name:String = "哈哈哈"
Log.e("TAG", (name as? String).toString())
输出信息:
2.输出null
E/TAG: 哈哈哈
var name:String = "哈哈哈"
Log.e("TAG", (name as? Int).toString())
输出信息:
E/TAG: null