Nice Features of Kotlin Part -1
Named & Default arguments, Data classes, Safe calls, String template and more…
Named and Default Arguments
- Default arguments simplify functions with longer arguments.
- 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
- Class with fixed number of instances.
- 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
- Safe call
?.
- Elvis
?:
- Non-null assertion
!!
(Use only if mandatory)
Data class
- Class to hold data
- Class Constructor should contain at-least one parameter
- Compiler only uses the properties defined inside the primary constructor for the automatically generated functions.
- Automatically generated functions are
equals()
,hashCode()
,toString()
,componentN()
copy()
is special automatically generated functions which allow to access properties declared in the body as well.