Do we need to initialize nullable fields in kotlin?










4















I have recently reviewed some kotlin codes, All nullable field initialized as null.



What is the difference between val x : String? = null and val x : String?



Should we initialize the nullable fields as null?










share|improve this question




























    4















    I have recently reviewed some kotlin codes, All nullable field initialized as null.



    What is the difference between val x : String? = null and val x : String?



    Should we initialize the nullable fields as null?










    share|improve this question


























      4












      4








      4








      I have recently reviewed some kotlin codes, All nullable field initialized as null.



      What is the difference between val x : String? = null and val x : String?



      Should we initialize the nullable fields as null?










      share|improve this question
















      I have recently reviewed some kotlin codes, All nullable field initialized as null.



      What is the difference between val x : String? = null and val x : String?



      Should we initialize the nullable fields as null?







      kotlin nullable






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 17 '18 at 8:20







      Samet Baskıcı

















      asked Nov 16 '18 at 7:31









      Samet BaskıcıSamet Baskıcı

      376415




      376415






















          3 Answers
          3






          active

          oldest

          votes


















          4














          Everything, even nullable variables and primitives, need to be initialized in Kotlin. You can, as tynn mentioned, mark them as abstract if you require overriding. If you have an interface, however, you don't have to initialize them. This won't compile:



          class Whatever 
          private var x: String?



          but this will:



          interface IWhatever 
          protected var x: String?



          This too:



          abstract class Whatever 
          protected abstract var x: String?



          If it's declared in a method, you don't have to initialize it directly, as long as it's initialized before it's accessed. This is the exactly same as in Java, if you're familiar with it.



          If you don't initialize it in the constructor, you need to use lateinit. Or, if you have a val, you can override get:



          val something: String?
          get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"


          As I opened with, even nullable variables need to be initialized. This is the way Kotlin is designed, and there's no way around that. So yes, you need to explicitly initialize the String as null, if you don't initialize it with something else right away.






          share|improve this answer






























            3














            val x : String? will create an uninitialized variable or property, depending on where it's defined. If it's in a class (rather than a function), it creates a property, and you cannot create an uninitalized property unless it's abstract. For example take this code:



            class MyClass 
            val x : String?



            This won't compile. You'll get Property must be initialized or be abstract.



            This code, however, will compile



            class MyClass 
            fun test()
            val x : String?




            However it's a bit pointless as you will not be able to refer to that variable: as soon as you do you'll get Variable 'x' must be initialized.



            So yes, generally when defining a nullable member you should initialize it (e.g. with a value of null), unless it's abstract, in which case the overriding class should initialize it.






            share|improve this answer






























              2














              A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.



              Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function ()
                StackExchange.using("externalEditor", function ()
                StackExchange.using("snippets", function ()
                StackExchange.snippets.init();
                );
                );
                , "code-snippets");

                StackExchange.ready(function()
                var channelOptions =
                tags: "".split(" "),
                id: "1"
                ;
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function()
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled)
                StackExchange.using("snippets", function()
                createEditor();
                );

                else
                createEditor();

                );

                function createEditor()
                StackExchange.prepareEditor(
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader:
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                ,
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                );



                );













                draft saved

                draft discarded


















                StackExchange.ready(
                function ()
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333293%2fdo-we-need-to-initialize-nullable-fields-in-kotlin%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                4














                Everything, even nullable variables and primitives, need to be initialized in Kotlin. You can, as tynn mentioned, mark them as abstract if you require overriding. If you have an interface, however, you don't have to initialize them. This won't compile:



                class Whatever 
                private var x: String?



                but this will:



                interface IWhatever 
                protected var x: String?



                This too:



                abstract class Whatever 
                protected abstract var x: String?



                If it's declared in a method, you don't have to initialize it directly, as long as it's initialized before it's accessed. This is the exactly same as in Java, if you're familiar with it.



                If you don't initialize it in the constructor, you need to use lateinit. Or, if you have a val, you can override get:



                val something: String?
                get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"


                As I opened with, even nullable variables need to be initialized. This is the way Kotlin is designed, and there's no way around that. So yes, you need to explicitly initialize the String as null, if you don't initialize it with something else right away.






                share|improve this answer



























                  4














                  Everything, even nullable variables and primitives, need to be initialized in Kotlin. You can, as tynn mentioned, mark them as abstract if you require overriding. If you have an interface, however, you don't have to initialize them. This won't compile:



                  class Whatever 
                  private var x: String?



                  but this will:



                  interface IWhatever 
                  protected var x: String?



                  This too:



                  abstract class Whatever 
                  protected abstract var x: String?



                  If it's declared in a method, you don't have to initialize it directly, as long as it's initialized before it's accessed. This is the exactly same as in Java, if you're familiar with it.



                  If you don't initialize it in the constructor, you need to use lateinit. Or, if you have a val, you can override get:



                  val something: String?
                  get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"


                  As I opened with, even nullable variables need to be initialized. This is the way Kotlin is designed, and there's no way around that. So yes, you need to explicitly initialize the String as null, if you don't initialize it with something else right away.






                  share|improve this answer

























                    4












                    4








                    4







                    Everything, even nullable variables and primitives, need to be initialized in Kotlin. You can, as tynn mentioned, mark them as abstract if you require overriding. If you have an interface, however, you don't have to initialize them. This won't compile:



                    class Whatever 
                    private var x: String?



                    but this will:



                    interface IWhatever 
                    protected var x: String?



                    This too:



                    abstract class Whatever 
                    protected abstract var x: String?



                    If it's declared in a method, you don't have to initialize it directly, as long as it's initialized before it's accessed. This is the exactly same as in Java, if you're familiar with it.



                    If you don't initialize it in the constructor, you need to use lateinit. Or, if you have a val, you can override get:



                    val something: String?
                    get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"


                    As I opened with, even nullable variables need to be initialized. This is the way Kotlin is designed, and there's no way around that. So yes, you need to explicitly initialize the String as null, if you don't initialize it with something else right away.






                    share|improve this answer













                    Everything, even nullable variables and primitives, need to be initialized in Kotlin. You can, as tynn mentioned, mark them as abstract if you require overriding. If you have an interface, however, you don't have to initialize them. This won't compile:



                    class Whatever 
                    private var x: String?



                    but this will:



                    interface IWhatever 
                    protected var x: String?



                    This too:



                    abstract class Whatever 
                    protected abstract var x: String?



                    If it's declared in a method, you don't have to initialize it directly, as long as it's initialized before it's accessed. This is the exactly same as in Java, if you're familiar with it.



                    If you don't initialize it in the constructor, you need to use lateinit. Or, if you have a val, you can override get:



                    val something: String?
                    get() = "Some fallback. This doesn't need initialization because the getter is overridden, but if you use a different field here, you naturally need to initialize that"


                    As I opened with, even nullable variables need to be initialized. This is the way Kotlin is designed, and there's no way around that. So yes, you need to explicitly initialize the String as null, if you don't initialize it with something else right away.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 16 '18 at 8:55









                    ZoeZoe

                    13k85085




                    13k85085























                        3














                        val x : String? will create an uninitialized variable or property, depending on where it's defined. If it's in a class (rather than a function), it creates a property, and you cannot create an uninitalized property unless it's abstract. For example take this code:



                        class MyClass 
                        val x : String?



                        This won't compile. You'll get Property must be initialized or be abstract.



                        This code, however, will compile



                        class MyClass 
                        fun test()
                        val x : String?




                        However it's a bit pointless as you will not be able to refer to that variable: as soon as you do you'll get Variable 'x' must be initialized.



                        So yes, generally when defining a nullable member you should initialize it (e.g. with a value of null), unless it's abstract, in which case the overriding class should initialize it.






                        share|improve this answer



























                          3














                          val x : String? will create an uninitialized variable or property, depending on where it's defined. If it's in a class (rather than a function), it creates a property, and you cannot create an uninitalized property unless it's abstract. For example take this code:



                          class MyClass 
                          val x : String?



                          This won't compile. You'll get Property must be initialized or be abstract.



                          This code, however, will compile



                          class MyClass 
                          fun test()
                          val x : String?




                          However it's a bit pointless as you will not be able to refer to that variable: as soon as you do you'll get Variable 'x' must be initialized.



                          So yes, generally when defining a nullable member you should initialize it (e.g. with a value of null), unless it's abstract, in which case the overriding class should initialize it.






                          share|improve this answer

























                            3












                            3








                            3







                            val x : String? will create an uninitialized variable or property, depending on where it's defined. If it's in a class (rather than a function), it creates a property, and you cannot create an uninitalized property unless it's abstract. For example take this code:



                            class MyClass 
                            val x : String?



                            This won't compile. You'll get Property must be initialized or be abstract.



                            This code, however, will compile



                            class MyClass 
                            fun test()
                            val x : String?




                            However it's a bit pointless as you will not be able to refer to that variable: as soon as you do you'll get Variable 'x' must be initialized.



                            So yes, generally when defining a nullable member you should initialize it (e.g. with a value of null), unless it's abstract, in which case the overriding class should initialize it.






                            share|improve this answer













                            val x : String? will create an uninitialized variable or property, depending on where it's defined. If it's in a class (rather than a function), it creates a property, and you cannot create an uninitalized property unless it's abstract. For example take this code:



                            class MyClass 
                            val x : String?



                            This won't compile. You'll get Property must be initialized or be abstract.



                            This code, however, will compile



                            class MyClass 
                            fun test()
                            val x : String?




                            However it's a bit pointless as you will not be able to refer to that variable: as soon as you do you'll get Variable 'x' must be initialized.



                            So yes, generally when defining a nullable member you should initialize it (e.g. with a value of null), unless it's abstract, in which case the overriding class should initialize it.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 16 '18 at 7:40









                            Yoni GibbsYoni Gibbs

                            1,528114




                            1,528114





















                                2














                                A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.



                                Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.






                                share|improve this answer



























                                  2














                                  A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.



                                  Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.






                                  share|improve this answer

























                                    2












                                    2








                                    2







                                    A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.



                                    Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.






                                    share|improve this answer













                                    A property must be initialized. Therefore you have to do the initialization var x : String? = null. Not assigning a value is only the declaration of the property and thus you'd have to make it abstract abstract val x : String?.



                                    Alternatively you can use lateinit, also on non-nullable types. But this has the effect, that it's not null, but uninitialized lateinit var x : String.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Nov 16 '18 at 7:40









                                    tynntynn

                                    20.9k54984




                                    20.9k54984



























                                        draft saved

                                        draft discarded
















































                                        Thanks for contributing an answer to Stack Overflow!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid


                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.

                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function ()
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53333293%2fdo-we-need-to-initialize-nullable-fields-in-kotlin%23new-answer', 'question_page');

                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        27

                                        Top Tejano songwriter Luis Silva dead of heart attack at 64

                                        Category:Rhetoric