Skip to content

Commit 63220f4

Browse files
update: add advice about as operator to java interop guide (#5078)
1 parent 269f14d commit 63220f4

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

docs/topics/jvm/java-to-kotlin-nullability-guide.md

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,50 @@ you would do the check anyway, but no additional boxing is performed this way.
339339
>
340340
{style="note"}
341341

342+
When migrating Java code to Kotlin, you may want to initially use the regular cast operator `as` with a nullable type
343+
to preserve the original semantics of your code. However, we recommend adapting your code to use the safe cast operator `as?`
344+
for a safer and more idiomatic approach. For example, if you have the following Java code:
345+
346+
```java
347+
public class UserProfile {
348+
Object data;
349+
350+
public static String getUsername(UserProfile profile) {
351+
if (profile == null) {
352+
return null;
353+
}
354+
return (String) profile.data;
355+
}
356+
}
357+
```
358+
359+
Migrating this directly with the `as` operator gives you:
360+
361+
```kotlin
362+
class UserProfile(var data: Any? = null)
363+
364+
fun getUsername(profile: UserProfile?): String? {
365+
if (profile == null) {
366+
return null
367+
}
368+
return profile.data as String?
369+
}
370+
```
371+
372+
Here, `profile.data` is cast to a nullable string using `as String?`.
373+
374+
We recommend going one step further and using `as? String` to safely cast the value. This approach returns `null`
375+
on failure instead of throwing a `ClassCastException`:
376+
377+
```kotlin
378+
class UserProfile(var data: Any? = null)
379+
380+
fun getUsername(profile: UserProfile?): String? =
381+
profile?.data as? String
382+
```
383+
384+
This version replaces the `if` expression with the [safe call operator](null-safety.md#safe-call-operator) `?.`, which safely accesses the data property before attempting the cast.
385+
342386
## What's next?
343387

344388
* Browse other [Kotlin idioms](idioms.md).

0 commit comments

Comments
 (0)