post cover

Named & Default arguments, Data classes, Safe calls, String template and more…

Named and Default Arguments

  1. Default arguments simplify functions with longer arguments.
  2. Named arguments improves code redability

String template

Programmatic way to generate a string

Operator Overloading

Custom implementations for the predefined set of operators on types.

Unary Operators

+a means a.unaryPlus()

-a means a.unaryMinus()

!a means a.not()

Increment & Decrement Operators

a++ means a.inc()

a-- means a.dec()

Arithmetic Operators

a + b means a.plus(b)

a - b means a.minus(b)

a * b means a.times(b)

a % b means a.rem(b)

a..b means a.rangeTo(b)

a % b means a.div(b)

Indexed Access Operators

a[i] means a.get(i)

Invoke Operator

a() means a.invoke()

a(i) means a.invoke(i)

Extension Function

Extension functions add additional member functions to the existing class without altering the class. Extension functions can access only the public members of the receiver type

Using when as statement and expression

It is conditional expression with multiple branches.

Using enums

  1. Class with fixed number of instances.
  2. Semicolon should be added at the last enum instance when we additionally include class members.

Dealing with null

To avoid null pointer exception in code, we can use some checks

  1. Safe call ?.
  2. Elvis ?:
  3. Non-null assertion !! (Use only if mandatory)

Data class

  1. Class to hold data
  2. Class Constructor should contain at-least one parameter
  3. Compiler only uses the properties defined inside the primary constructor for the automatically generated functions.
  4. Automatically generated functions are equals(), hashCode(), toString(), componentN()
  5. copy() is special automatically generated functions which allow to access properties declared in the body as well.