Kiryushin Andrey
01/28/2020, 9:01 AM.?
) in Kotlin vs the similar operator in C#. Say we have such classes
data class Head(val name: String)
data class Department(val head: Head)
data class Employee(val department: Department)
and the variable e
of type Employee?
.
Kotlin will refuse to compile an expression e?.department.head.name
complaining that head
property cannot be accessed on an instance of Department?
type. So this expression needs to be rewritten as e?.department?.head?.name
, which in my opinion looks a bit clumsy cause we know in advance that the only thing in this chain that can possibly be null is e
.
In C#, on the other hand, this operator discards the whole chain if null is encountered, compiling e?.Department.Head.Name
to (e != null) ? e.Department.Head.Name : null
.
Am I missing something or does C# really do a better job in this case? Is this difference in behavior due to the fact that it was hard or impossible to to implement a C#-like behavior given null-aware type system? Or maybe there are some other cases when this Kotlin compiler behavior allows for safer code and therefore is desired? Would like to hear the community as well as JetBrains folks' thoughts on this.dmitriy.novozhilov
01/28/2020, 9:06 AMDepartment
, so call without ?
may be resolved to it
class Employee(val department: Department)
class Department {
val name: String = "Member"
}
val Department?.name: String get() = "Extension"
fun test(e: Employee?) {
e?.department?.name // Member
e?.department.name // Extenstion
}
dmitriy.novozhilov
01/28/2020, 9:09 AMKiryushin Andrey
01/28/2020, 9:13 AMdmitriy.novozhilov
01/28/2020, 9:18 AMclass A(val x: Int)
val A.x: String get() = ""
Declaring extension with same as member name but on nullable receiver useful when you have some nullable field and default value for it, but you don't want to write that value to object for some reason