How to get the default value of a type in Kotlin?

Asked

Viewed 84 times

1

I’m coming from C# and starting working with Kotlin (Android). In C#, if I want the default expected value for a type I should call it as in the example below:

class Foo {}

class Main 
{
    public static void Main(string[] args) 
    {
        var d_string   = default(string)   // = null
        var d_int      = default(int)      // = 0
        var d_bool     = default(bool)     // = false
        var d_DateTime = default(DateTime) // = 1/1/0001 12:00:00 AM
        var d_Foo      = default(Foo)      // = null
    }
}    

I wonder if there is any way to return the default value of a type as in the example above in Kotlin.

1 answer

1


Kotlin has nothing like it, and the way out is to use the literal

Usually it is a value 0, some type of 0, not necessarily 0.

This means your C# assumptions for string and Foo are wrong. Because they are types by reference, so their value is a pointer, their 0 is a null value, not an empty text, much less the type object. Already 0, false and a calendar start time that is not well is an internal zero even if the textual representation shows how day 1 of month 1 and year 1 are values that can be considered 0. It has a table theirs.

I’ll leave this text here because this user has a habit of asking the wrong question and then fixing, then it seems that the answer speaks of things that do not exist in the question.

In Kotlin should all be equal values, but it would be good to confirm. If it is not I will start to find Kotlin weird, even more that in Java is equal to C#.

In the vast majority of cases it makes more sense to use a default(T) or some way like that because you don’t know what type it is, even in C# when you know the type it makes little sense to use this form and not the literal. It may even be in some case where you want to facilitate a change or want to ensure that something doesn’t compile if you use an improper value for that type, which is rarely a real problem. It is also possible to use the default alone when the compiler can infer the type, then it makes a little more sense, but very little, I prefer to use the literal.

So go without fear in the literal of the same type, mainly because there is not even a justification in the question to use different.

  • I understand that the above codes were wrong so much that I even corrected them, the point is that I was looking for the resource default(T) inside the Kotlin.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.