问题
In Java, I can write code like:
void cast(A a) {
if(a instanceof Person) {
Person p = (Person) a;
}
}
In Kotlin, what should I do?
Use as
operator or is
operator?
回答1:
is X
is the equivalent of instanceof X
foo as X
is the equivalent of ((X) foo)
Additionally, Kotlin performs smart casting where possible, so no additional cast needed after you check the type using is
:
open class Person : A() {
val foo: Int = 42
}
open class A
and then:
if (p is Person) {
println(p.foo) // look, no cast needed to access `foo`
}
回答2:
is
is type checking. But Kotlin has smart cast which means you can use a
like Person
after type check.
if(a is Person) {
// a is now treated as Person
}
as
is type casting. However, as
is not recommended because it does not guarantee run-time safety. (You may pass a wrong object which cannot be detected at compiled time.)
Kotlin has a safe cast as?
. If it cannot be casted, it will return null instead.
val p = a as? Person
p?.foo()
回答3:
"Kotlin in action" by Dmitry Jemerov and Svetlana Isakova has a good example of as and is:
回答4:
As per Kotline official documents
Usually, the cast operator throws an exception if the cast is not possible. Thus, we call it unsafe. The unsafe cast in Kotlin is done by the infix operator as
val x: String = y as String
Note that null cannot be cast to String as this type is not nullable, i.e. if y is null, the code above throws an exception. In order to match Java cast semantics we have to have nullable type at cast right hand side, like:
val x: String? = y as String?
So here use is instead of as
fun cast(a: A) {
if (a is Person) {
val p = a as Person
}
}
回答5:
as
is used for explicit type casting
val p = a as Person;
is
is exactly the same as instanceof
in Java. Which is used to check if an object is an instance of a class
if(a is Person) {
// a is an instance of Person
}
You can also used !is
as is it not an object of a class
fun cast(a: A) {
if(a is Person) {
val p = a as Person;
}
}
回答6:
is Operator is checking datatype
but as is for casting to some type for example casting Int to String
回答7:
so
if(a is Person){
a as Person
}else{
null
}
equivalent
a as? Person
Is this answer?
回答8:
you can use is operator
fun cast(a:A){
if (a is Person){
var person = a
}
}
回答9:
is - To check if an object is of a certain type
Example:
if (obj is String) {
print(obj.length)
}
as - To cast an object to a potential parent type
Example:
val x: String = y as String
val x: String? = y as String?
val x: String? = y as? String
Reference: https://kotlinlang.org/docs/reference/typecasts.html
来源:https://stackoverflow.com/questions/47067302/what-is-difference-between-as-and-is-operator-in-kotlin