Droid .kt
what are the keywords in Scoping functions
(run,also,let,with,apply)
Adavantages of Kotlin over Java
> concise - Kotlin reduces writing extra codes. This make Kotlin concise > null safety - Kotlin null safety language. It aims to eliminate nullPointException. > interoperable - it is able to use Java code in Kotlin and it is able to use Kotlin code in Java > It has better performance and fast compilation time.
transient
@Target([AnnotationTarget.FIELD]) annotation class Transient Marks the JVM backing field of the annotated property as transient, meaning that it is not part of the default serialized form of the object.
Different type of constructor in kotlin
A constructor is a concise way to initialize class properties. In Kotlin, there are two constructors: Primary constructor - concise way to initialize a class Secondary constructor - allows you to put additional initialization logic Secondary constructors are not that common in Kotlin. The most common use of secondary constructor comes up when you need to extend a class that provides multiple constructors that initialize the class in different ways.
High Order Functions
A function that takes in function as an argument or returns a function. Var values = listOf<Int>( 1,2,3,4,5) values.forEach({ n -> println(n)}) // calling a function inside a function. values.forEach(::println) values.forEach({println(it)}) https://www.javatpoint.com/kotlin-higher-order-function
Use of Abstraction in kotlin
An abstract class cannot be instantiated (you cannot create objects of an abstract class). However, you can inherit subclasses from them.
Inline Functions vs Infix functions
An inline function therefore is a function whose body and it's lambda argument's body will be inlined to the call-site at compile time. The use of inline function enhances the performance of higher order function. In order to reduce the memory overhead of high order functions. https://www.javatpoint.com/kotlin-inline-function https://android.jlelse.eu/learning-kotlin-inline-functions-18a94d3efe46
how kotlin - java interoperability possible?
As Kotlin is completely compatible with Java language. It means the application written in Java code can be easily called from Kotlin. In the similar way ,Kotlin code is also called Java code.
@JvmStatic , @Singleton
As mentioned above, Kotlin represents package-level functions as static methods. Kotlin can also generate static methods for functions defined in named objects or companion objects if you annotate those functions as @JvmStatic. If you use this annotation, the compiler will generate both a static method in the enclosing class of the object and an instance method in the object itself. class C { companion object { @JvmStatic fun callStatic() {} fun callNonStatic() {} } } Now, callStatic() is static in Java, while callNonStatic() is not: C.callStatic(); // works fine C.callNonStatic(); // error: not a static method C.Companion.callStatic(); // instance method remains C.Companion.callNonStatic(); // the only way it works The @Singleton annotation is used to mark the class as Singleton hence allowing a single instance of the class. https://blog.mindorks.com/jvmstatic-jvmoverloads-and-jvmfield-in-kotlin
Backing Fields / Backing Properties
Backing field is generated only if a property uses the default implementation of getter/setter. In Kotlin the above code snippet will throw StackOverflow because when we access or set property firstName or lastName the default accessor will be called. So in Kotlin user.firstName = "value" is same as Java's user.setFirstName("value"). So when set(value) {firstName = "value"} is called, then a recursive call happens and compiler throws a StackOverflow exception because we are calling setter inside the setter. Classes in Kotlin cannot have fields. However, sometimes it is necessary to have a backing field when using custom accessors. For these purposes, Kotlin provides an automatic backing field which can be accessed using the field identifier. var selectedColor: Int = someDefaultValue get() = field set(value) { field = value } field generated for a property in a class only if it uses default implementation of at least one of the accessors. https://medium.com/@nomanr/backing-field-in-kotlin-explained-9f903f27946c
Class Reference
Class reference is used to obtain the reference of a KClass object. To obtain the reference of statically Kclass, we should use the class literal(i.e. use double colons). Syntax of class reference: val c1 = String::class val c2 = MyClass::class The reference value is a class type of KClass. KClass class reference is not the same as a Java class reference. We obtain the Java class reference by using .java property on a KClass instance. **If two objects have the same hashcode then they are NOT necessarily equal. Otherwise you will have discovered the perfect hash function. But the opposite is true: if the objects are equal, then they must have the same hashcode .
Enum Classes
Enumerations in Kotlin are data types that hold a set of constants. Enums are defined by adding the modifier enum in front of a class. Here are some important points about enum classes in kotlin. Each enum constant is an object. Enum constants are separated by commas. Each of the enum constants acts as separate instances of the class. Enums are useful in enhancing the readability of your code since it assigns pre-defined names to constants. Unlike classes, an instance of enum classes cannot be created using constructors. Hence, we can assert that enum classes are abstract.
Extension functions
Extension function is used to extend the functionality of a class just by Class.function(). Kotlin extension function provides a facility to "add" methods to class without inheriting a class or using any type of design pattern. https://www.javatpoint.com/kotlin-extension-function
Data class , Pair , Triple , copy
For data class, the compiler automatically generates: getters and setters copy() function, equals() and hashCode() pair, and toString() form of the primary constructor componentN() functions Pair is used to store or return two values of the same or different data types. There can or cannot be any relation between both the values. var pair = Pair("Hello", "How are you") println(pair.first) println(pair.second) println(pair.component1()) println(pair.component2()) Triple is used to store or return three values of the same or different data types. There can or cannot be any relation between both the values.. pair and tripple : just like data class; but holds 2-3 values.
Difference between == & === in kotlin
For referential equality, we use the === symbol which allows us to evaluate the reference of an object (if it's pointing to the same object). Now for structural equality, we use the == symbol that evaluates if both values are the same (or equal).
Generics & Reified types
Generics are the powerful features that allow us to define classes, methods and properties which are accessible using different data types while keeping a check of the compile-time type safety. class Person<T>(age: T){ var age: T = age init { this.age= age println(age) } } fun main(args: Array<String>){ var ageInt: Person<Int> = Person<Int>(30) var ageString: Person<String> = Person<String>("40") } Output: 30 40 Reification allows you to preserve the generic type in runtime. Kotlin supports reification of parameter types in a function under a certain condition, that being the function is an inline function.
companion object
If you want to write a function or any member of the class that can be called without having the instance of the class then you can write the same as a member of a companion object inside the class. If you need a function or a property to be tied to a class rather than to instances of it, you can declare it inside a companion object:
What is Unit , Any , Nothing in Kotlin?
In Java if we want that a function does return nothing we use void, Unit is the equivalent in Kotlin. Object
Open keyword
In Kotlin by default all the classes are final which means they are not- inheritable, so for Inheritance, we need to use a keyword open in your class.
Inner Class
Inner class is a class which is created inside another class with keyword inner. The advantage of inner class over nested class is that it is able to access members of outer class even if it is private. Inner class keeps a reference to an object of outer class.
DSL (Domain Specific Language)
Kotlin gives you the tools to help craft code into something which feels more natural to use, through a domain-specific language — or DSL!
Delegations / Delegated Properties
Kotlin supports "delegation" design pattern by introducing a new keyword "by". Using this keyword or delegation methodology, Kotlin allows the derived class to access all the implemented public methods of an interface through a specific object. Then the magic keyword is by. interface Base { fun printMe() //abstract method } class BaseImpl(val x: Int) : Base { override fun printMe() { println(x) } //implementation of the method } class Derived(b: Base) : Base by b // delegating the public method on the object b fun main(args: Array<String>) { val b = BaseImpl(10) Derived(b).printMe() // prints 10 :: accessing the printMe() method }
Nullable & Non Nullable Types
Kotlin types system differentiates between references which can hold null (nullable reference) and which cannot hold null (non null reference). Normally,types of String are not nullable. To make a string which holds null value, we have to explicitly define them by putting a ? behind the String as: String? !!
Nested Classes
Nested class is a class which is created inside another class. In Kotlin, nested class is by default static, so its data member and member function can be accessed without creating an object of class. Nested class cannot be able to access the data member of outer class.
does kotlin support checked exception?
No Exception leads to program termination. Exception handling is used to handle this problem. Exception handling is to maintain the flow of program execution. Unchecked exception is that exception which is thrown due to mistakes in our code. It is checked at runtime. Checked exception is checked at compile time. (IOException , SQLException)
Is a new keyword used in kotlin ? How can we instantiate a class object in kotlin?
No. We can instantiate by using val or var and name of the object which would be equal to the Classname().
What is Kotlin Reflection?
Reflection is a set of language and library features that examines the structure of a program at runtime. Kotlin makes functions and properties as first-class citizens in the language and examines these functions and properties at runtime.
What are Sealed Class?
Sealed Classes allow us to fix type hierarchies and forbid developers from creating new subclasses.
Sealed class rules?
Sealed classes are abstract and can have abstract members. Sealed classes cannot be instantiated directly. Sealed classes cannot have public constructors (The constructors are private by default). Sealed classes can have subclasses, but they must either be in the same file or nested inside of the sealed class declaration. Sealed classes subclass can have subclasses outside of the sealed class file. https://proandroiddev.com/understanding-kotlin-sealed-classes-65c0adad7015 https://www.raywenderlich.com/75657-kotlin-sealed-classes#toc-anchor-001
smart cast
Smart cast is a feature in which Kotlin compiler tracks conditions inside an expression. If the compiler finds a variable is not null of type nullable then the compiler will allow access to the variable. "As" operator for smart casts. When we try to access a nullable type of String without safe cast it will generate a compile error. var string: String? = "Hello!" print(string.length) // Compile error To solve the above expression we use a safe cast as: fun main(args: Array<String>){ var string: String? = "Hello!" if(string != null) { // smart cast print(string.length) // It works now! } } In Kotlin, You can check whether an object is of a certain type at runtime by using the is operator. Kotlin also provides a Safe cast operator as? that returns null instead of throwing a ClassCastException if the casting is not possible . https://www.callicoder.com/kotlin-type-checks-smart-casts/
Elvis Operator , range operator
Sometimes, when we have a reference, we want to return some default value from the operation if the reference holds a null. The elvis operator (?:) will evaluate the left side of the expression and will return it if it is not null, otherwise it will return the right side of the expression. Kotlin Elvis Operator example fun main(args: Array<String>){ var str: String? = null var str2: String? = "May be declare nullable string" var len1: Int = str ?.length ?: -1 var len2: Int = str2 ?.length ?: -1 println("Length of str is ${len1}") println("Length of str2 is ${len2}") } Output: Length of str is -1 Length of str2 is 30 val b = a?.length ?: -1 If the expression to the left of ?: (here : a?.length) is not null, the elvis operator returns it, otherwise it returns the expression to the right (here: -1). Right-hand side expression is evaluated only if the left-hand side is null. Kotlin range is defined as an interval from start value to the end value. Range expressions are created with operator (. .)
Tail recursion
Tail recursion is a recursion which performs the calculation first, then makes the recursive call. The result of the current step is passed into the next recursive call. Tail recursion follows one rule for implementation. This rule is as follow: The recursive call must be the last call of the method. To declare a recursion as tail recursion we need to use tailrec modifier before Kotlin Tail Recursion Example 2: calculating factorial of number Let's see an example of calculating factorial of number using tail recursion. fun main(args: Array<String>) { val number = 4 val result: Long result = factorial(number) println("Factorial of $number = $result") } tailrec fun factorial(n: Int, run: Int = 1): Long { return if (n == 1){ run.toLong() } else { factorial(n-1, run*n) } } Output: Factorial of 4 = 24
What is associateWith() function in kotlin?
The basic association function associateWith() creates a Map in which the elements of the original collection are keys, and values are produced from them by the given transformation function.
What is the flatten () function in kotlin?
The first function is flatten(). You can call it on a collection of collections, for example, a List of Sets. The function returns a single List of all the elements of the nested collections.
Lateinit & byLazy
The lateinit indicates that this property won't have value from the beginning, but will be assigned before it's used (otherwise it'll throw an exception). Using Lazy() Lazy is a lambda function which takes a property as an input and in return gives an instance of Lazy<T>, where <T> is basically the type of the properties it is using. > variable will not be initialized unless you use that variable. > it will be initialized only once. > it use val. Live Demo val myVar: String by lazy { "Hello" } fun main(args: Array<String>) { println(myVar +" My dear friend") } In the above piece of code, we are passing a variable "myVar" to the Lazy function, which in return assigns the value to its object and returns the same to the main function. Following is the output in the browser. Hello My dear friend https://blog.mindorks.com/learn-kotlin-lateinit-vs-lazy
What is map() in kotlin?
The mapping transformation creates a collection from the results of a function on the elements of another collection. The basic mapping function is map().
singleton class in kotlin
The singleton pattern restricts the instantiation of a class to a single object. It is useful in cases wherein you only need a single object to contain a global state. To create a singleton, one has to make sure that Only one instance can exist It has global access The object keyword in Kotlin is to create a class with just a single instance. Considerations and Limitations A major thing to consider when using an object is that it does not have constructors. This is because they are instantiated on class reference.
What is the equivalent to switch case of Java in kotlin ?
The when construct in Kotlin can be thought of as a replacement for Java switch Statement. It evaluates a section of code among many alternatives.
Why are sealed classes helpful?
They are useful when you have a very strict inheritance hierarchy, with a specific set of possible subclasses and no others. The compiler guarantees that only classes defined in the same source file as the sealed class are able to inherit from it.
What's the init block ?
To put the initialization code (not only code to initialize properties), the initializer block is used. It is prefixed with init keyword. Initializer block contains the code that is always executed whenever an instance is created. The code inside the init block is the first to be executed when the class is instantiated. The init block is run every time the class is instantiated, with any kind of constructor as we shall see next. Multiple initializer blocks can be written in a class. They'll be executed sequentially as shown below. role of init block in aiding primary constructor
visibility modifiers (internal)
Visibility modifiers are keywords that set the visibility (accessibility) of classes, objects, interface, constructors, functions, properties and their setters. Modifier Description public are visible everywhere private visible inside the file containing the declaration internal visible inside the same module (a set of Kotlin files compiled together) protected not available for packages (used for subclasses) private means visible inside this class only (including all its members); protected — same as private + visible in subclasses too; internal — any client inside this module who sees the declaring class sees its internal members; public — any client who sees the declaring class sees its public members.
does kotlin support primitive data types?
Yes
What is the Zip() extension function in kotlin?
Zipping transformation is building pairs from elements with the same positions in both collections. In the Kotlin standard library, this is done by the zip() extension function.
Scoping functions (run,also,let,with,apply)
functions whose sole purpose is to execute a block of code within the context of an object. When you call such a function on an object with a lambda expression provided, it forms a temporary scope. In this scope, you can access the object without its name. https://www.callicoder.com/kotlin-type-checks-smart-casts/ https://kotlinlang.org/docs/reference/scope-functions.html
What is joinToString & joinTo in kotlin ?
joinToString() builds a single String from the collection elements based on the provided arguments.
val , var & const
var (Mutable variable): We can change the value of a variable declared using var keyword later in the program. val (Immutable variable): We cannot change the value of a variable which is declared using the val keyword. 'const' keyword is used to define compile time constants,I.e, the value of the const variable is known at compile time. Whereas 'val' is used to define constants at run time. https://www.baeldung.com/kotlin-const-var-and-val-keywords