Define default value for a type

Maybe could be useful can define default value for a types for delete boilerplate

Example:


class Person {
  var name: String = ""
  var lastName: String = ""
  var address: String = ""
}
String.default  =  ""

class Person {
  var name := String
  var lastName := String
  var address := String
}

When you use ** := ** you must import the default value from a file

1 Like

+1 I’m also struggling with this; especially how to deal with generics if there is no defaults in kotlin (is there?). If there is generic property, does it need to be forced into a nullable, to be able to initialize it? And everything needs dummy =null? looking for something like default(T) in c#

“Default” values as you suggest are often poor design. The philosophy is that the object is always in a valid state except while executing the constructor (and finalizer). Basically all values are provided by the constructor based on its parameters. The primary constructor syntax with variables is a concrete push towards this concept. The only way to initialize generics is when the generic value is assigned through the constructor as it disappears at runtime and the class cannot interrogate its generic parameters.

In the absence of “default” values, how would one go about safely returning in the below method?

It’s implementing Hazelcast’s MapLoader<K, V>

override fun load(key : K) : V
{
    // key is nullable
    if (key == null) { return default(V); }

    ...
}

The question is “What does key== null even mean? What are you trying to access and what should be the result”.
There are only two options (as far as I can tell)

  1. null is a valid key, therefor it should be handled like any other
  2. null is an invalid key, therefor the code should raise an exception

So let’s say you have a different use case that needs default values. The only way I know is to pass in the default value. You could do that when creating your MapLoader object or if you have control over the function API add it as an additional parameter.

1 Like

That’s the point of generics (I think), it can be anything, and it’s fine if it’s null

If key is null, then my fun should return immediately, right now I hacked it with the default value, but imho there should be a more elegant solution