Skip to content

Instantly share code, notes, and snippets.

@serihiro
Last active January 1, 2022 12:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save serihiro/e9c96edd0483057333835f78ec3e309d to your computer and use it in GitHub Desktop.
Save serihiro/e9c96edd0483057333835f78ec3e309d to your computer and use it in GitHub Desktop.
Hot to smart-cast a Java class variable in Kotlin
import javax.annotation.Nullable;
public class Employee {
private String firstName;
private String lastName;
private Integer age;
public Employee(String firstName, String lastName, Integer age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
@Nullable
public String getFirstName() {
return firstName;
}
@Nullable
public String getLastName() {
return lastName;
}
@Nullable
public Integer getAge() {
return age;
}
}
/*
* This Kotlin source file was generated by the Gradle 'init' task.
*/
package com.github.serihiro
fun main() {
// val e = Employee("a", "b", 3)
// val canNotCompile1 = e.age + 3 // can not call nullable age
// val canNotCompile2 = if (e.age != null) {
// e.age + 3 // can not call nullable age even if after null checked.
// } else {
// 0
// }
// Approach 1: Assign a Java variable to a Kotlin variable
val e1 = Employee("a", "b", 3)
val tmpAge = e1.age
val age = if (tmpAge != null){
tmpAge + 3
} else {
0
}
println(age)
// Approach 2: Create a kotlin wrapper class
val e2 = KtEmployee("a", "b", null)
val tmpAge2 = e2.age()?.plus(3) ?: 0
println(tmpAge2)
}
class KtEmployee {
private val e: Employee
constructor(fistName: String?, lastName: String?, age: Int?) {
this.e = Employee(fistName, lastName, age)
}
fun fistName(): String? = e.firstName
fun lastName(): String? = e.lastName
fun age(): Int? = e.age
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment