What is happening here? Accessing null inside class??? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

What is happening here? Accessing null inside class???

class Test (var something: String){ // Compiler warns: Receiver parameter is never used // But it is necessary to let the following work. val Test?.something get() = "CCC" fun someMethode() { var test: Test? = null println(test.something) // works, prints CCC println(null.something) // works also, prints CCC test = Test("BBB") println(test.something) // now prints BBB test = null println(test.something) // now prints again CCC } } fun main() { val test1 = Test("AAA") println(test1.something) // prints AAA test1.someMethode() val test2: Test? = null // println(test2.something) won't compile } https://code.sololearn.com/cl4aFZji8eE8/?ref=app

24th Oct 2020, 2:49 PM
Johann
Johann - avatar
1 Answer
+ 2
So i wont say Kotlin is my main language but i love the simplicity that it gives to some of the syntax that it uses. test2.something needs to be test2?.something, you cant set something to a null and expect it not to yell at you when its outside of the class.
28th Oct 2020, 3:11 PM
Tristen Diaz
Tristen Diaz - avatar