/*关于问号 和 感叹号*/
fun aboutQuestionAndExclamationMark(){
var a = "za"
// null can't be a value of a none-null-type string ->
// null is not a string type
// null is a type of null ,String is a type of String
// var b : String = null
// we know behind the : is the type of an value ,
// the type of String? can point to both null value and a string value
//
var c : String? = null
var d : String? = "aa"
// error : type mismatch required String found String?
// var f : String = c
//String is a type of value ,String? is a type of value
//从可以指向的数据类型来看 String? 比 String 多了一个 null 类型的数据
//但是 有点像 java中的多态,String? 既可以指向 String 也可以指向 null
//但是 String 和 null 类型的指针 都不能指向 String?
// if you certainly know the value of variable c is the type of String ,
// you can use !! to tell IDE don't show error hint here,
// but in fact the value type of c is null ,
//and there will throw a kotlinNullPointerException
var g : String = c!!
}
String!
当一个kotlin的变量指向一个java的String类型的数据是,IDE会自动把java的String 转变成 这种类型。这种类型只有IDE可以指定,是无法手动指定的。如果这个类型的值报空指针,报的是 java.lang.nullPointerException.
!!
var value4 : String? = null
value4?.length
value4!!.length
// !!表示一种声明:声明value4是String类型,声明给IDE(or编译器)的,
//实际上value4该是什么还是什么,如果是null,运行时就会报错
网友评论