B4J Question Null parameters.

LucaMs

Expert
Licensed User
Longtime User
My question is written as comment line.

B4X:
    Type tTest(Elems As List)
    Private objTest As tTest

    objTest = CreatetTest(Null)

B4X:
Public Sub CreatetTest (Elems As List) As tTest
    Dim t1 As tTest
    t1.Initialize

'    If Elems = Null Then ' Why Elems is not Null here and I have to use the next line?
    If Elems.IsInitialized = False Then
        Elems.Initialize
    End If
    t1.Elems = Elems
    Return t1
End Sub

More than a question it is a fact, but it doesn't seem very correct to me.



Note (for the picky ones like me šŸ˜„): obviously I would never create a custom type like that, with only one "field".
 
Last edited:

EnriqueGonzalez

Well-Known Member
Licensed User
Longtime User
List and Maps are difficult to handle on Java. to treat them as a the core lib do, You have to create an object and a b4x list separetely and wrap the object inside the list.
Thats why you have to call isInitialized. i am pretty sure that no other classes or types has that problem (Strings and nulls are also complicated)
 
Upvote 0

William Lancee

Well-Known Member
Licensed User
Longtime User
https://softwareengineering.stackex... null by default,error when they are accessed.


What is the difference between uninitialized object variable and object variable initialized to null in Java?

There is no difference for class fields. They are null by default for objects, 0 for numeric values and false for booleans.

For variables declared in methods - Java requires them to be initialized. Not initializing them causes a compile time error when they are accessed.

What's the reason? Class fields can be modified by any method. In any order the method is invoked. All non-private fields may be modified by other classes and/or classes extending that class. Hence, there is no point in notifying about an uninitialized variable, since it may be assigned in many, many places.

Variables inside methods, however, are local and can be modified only inside the method itself. Hence it is both possible and rational to point possible mistakes. And the compiler tries to do it. If it knows the field is not initialized, it will show an error, because that's never what you want. If it is not sure - it will give a warning, so that you can make sure.
 
Upvote 0
Top