Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
51 views
44 pages
Inter 1
Uploaded by
MURALI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save Inter 1 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
0 ratings
0% found this document useful (0 votes)
51 views
44 pages
Inter 1
Uploaded by
MURALI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save Inter 1 For Later
0%
0% found this document useful, undefined
0%
, undefined
Embed
Share
Print
Report
Download now
Download
You are on page 1
/ 44
Search
Fullscreen
To view the live version of the Page, © Copyright by InterviewbitKotlin Interview Questions for Freshers 1. What are the various data types available in Kotlin? Explain them. 2. Howare variables declared in Kotlin? What are the different types of variables in Kotlin? Explain with examples. 3. What are data classes in Kotlin? Explain with a proper example. 4. Explain the concept of null safety in Kotlin. 5. Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin. 6. Differentiate between Kotlin and Java. 7. What are the different types of constructors available in Kotlin? Explain them with proper examples. 8. Explain the various methods to iterate over any data structure in Kotlin with examples. b2 How can you concatenate two strings in Kotlin? 10. What do you understand about function extension in the context of Kotlin? Explain. 11. What do you understand about Companion Object in the context of Kotlin? 12. Differentiate between open and public keywords in Kotlin. 13. Explain about the “when” keyword in the context of Kotlin. 14. What are the advantages of Kotlin over Java? Kotlin Interview Questions for Experienced 15. Which one is better to use - val mutableList or var immutableList in the context of Kotlin? 16. What do you understand about lateinit in Kotlin? When would you consider using it? 17. Explain lazy initialization in the context of Kotlin. Page Bhould use lateinit and when you should use lazy initialisatiodopyright by Interviewbitom ran tysid Kotlin Interview Questions Kotlin Interview Questions for Experienced 19. 20. 21. 22 23. 24, 25. .Continued) What do you understand about coroutines in the context of Kotlin? Explain scope functions in the context of Kotlin. What are the different types of Scope functions available in Kotlin? Explain suspend function in the context of Kotlin. What do you understand about sealed classes in Kotlin? What do you understand about the backing field in Kotlin? Differentiate between launch / join and async / await in Kotlin. What are some of the disadvantages of Kotlin? Page2 © Copyright by Interviewbitlee lala Cte Kotlin is an open-source, general-purpose, statically typed programming language. It is JVM-based and may be used in all projects where Java is currently used. It may be used to create Android apps, server-side apps, and a variety of other applications. It is an improved version of Java and is completely interoperable with it. We can even mix Kotlin and Java in the same project. It blends Object Oriented Programming (OOPs) and functional programming in a platform that is unlimited, self-contained, and unique. It also enables functional twinning using microcodes. The JetBrains team created Kotlin. The language was initially launched in February 2016 after a project began in 2010 to develop it. The Apache 2.0 license was used to create Kotlin. Programs written in Kotlin do not require semicolons. This makes the code more readable and easy to understand. This language enables the interchange and usage of Java in a variety of ways. Furthermore, code written in Java and Kotlin can coexist in the same project. The type system of Kotlin is designed to eliminate NullPointerException from code. Writing new code in Kotlin will take you less time. Kotlin code is even easier to deploy and manage at scale. Following are the features of Kotlin:- — Kotlin 283s InterviewBit Page3 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Compact code: Kotlin is an OOPs-based programming language with code lines that may be reduced by up to 40% when compared to Java, making it an excellent choice for software development. Open Source: Kotlin for Android is open-source and uses the JVM to combine the benefits of OOPs and functional programming. Simple Language: When working with Kotlin, compiling the code is simple, resulting in improved performance for Android development. It also explains which types of data functions can be used throughout the code. High number of extensions: Without modifying the code, Kotlin may support a variety of extension functions. It aids developers in making existing code more appealing and wonderful. Full Java Interoperability: Java code can utilize Kotlin code, and Kotlin code can use Java code. So, if you're familiar with OOPS programming, switching to Kotlin development is simple. Also, if there are any Java-based applications, they can be used with Kotlin's environment. Smart Cast: Smart casting is a technique that reduces the cost of an application while also improving its speed and performance. It uses typecasting or immutable data to manage the efficiency of programming. This technique is supported by Kotlin. Low Learning Curve: Kotlin is preferred by businesses due to its low adoption cost. Most significantly, it is simple for developers to learn, especially if they have programming experience. Learn More. Kotlin Interview Questions for Freshers 1. What are the various data types available in Kotlin? Explain them. Primitive data types are the most basic data types in Kotlin, and all others are reference types like array and string. Kotlin contains all data types as objects. Following are the different data types available in Kotlin:- Page 4 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Boolean Character | Number String Array Byte Short Int Long Double Float 28s Interviewsit Integer Data Type - Data Type Space Required byte 8 bits short 16 bits int 32 bits long 64 bits Floating Point Data Type - Pages © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Data Type Space Required float 32 bits double 64 bits Boolean Data Type - True or false is the only bit of information represented by the Boolean data type. In Kotlin, the Boolean type is the same as in Java. Data Type Space Required boolean 1 bit Character Data Type - Small letters (a-z), capital letters (A-Z), numerals (0-9), and other symbols are represented by the character data type. Data Type Space Required char 8 bits String Data Type - Strings are represented in Kotlin by the type String. A string value is often a sequence of characters enclosed in double quotations ("). The space required in this case depends on the number of characters in the string. Array Data Type - Pages © Copyright by Interviewbitom ran tysid Kotlin Interview Questions The Array class in Kotlin is used to represent arrays. It has the get and set functions that, due to operator overloading conventions, can be used as ‘[]’ as well. The space required by the array also depends on the number of elements it posses. 2. How are variables declared in Kotlin? What are the different types of variables in Kotlin? Explain with examples. Every variable in Kotlin must be declared before it can be used. An attempt to use a variable without declaring it results in a syntax error. The type of data you are authorised to put in the memory address is determined by the variable type declaration. The type of variable can be determined from the initialised value in the case of local variables. For example, var site = "interviewbit" The above code declares a variable “site” of type String because the value with which the variable is initialised is a String. There are broadly two types of variables in Kotlin. They are as follows:- 2 InterviewBit Page7 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions © Immutable Variables — Immutable variables are also known as read-only variables. They are declared using the val keyword. Once these variables have been declared, we cannot change their values. The syntax is as follows : val variableName = value For example, val sample = "interview" sample = "interviewbit" // results in compile time error The second line in the above code snippet would result in a compile-time error as expected. Because it can be initialized with the value of a variable, an immutable variable is not a constant. It means that the value of an immutable variable does not need to be known at compile-time and that if it is defined inside a construct that is called several times, it can take on a different value with each function call. For example, var sample = "interview" val newSample = sample // no compile time error The above code snippet runs fine and does not produce any errors. © Mutable Variables - In a mutable variable, the value of the variable can be changed. We use the keyword “var” to declare such variables. The syntax is as follows : var variableName = value For example, Pages © Copyright by Interviewbitom ran tysid Kotlin Interview Questions var sample = "interview" sample = "fun" // no compile time error The above code snippet runs fine and does not produce any errors. 3. What are data classes in Kotlin? Explain with a proper example. The Data class is a simple class that holds data and provides typical functions. To declare a class as a data class, use the data keyword. Syntax: data class className ( list_of_parameters) The following functions are automatically derived by the compiler for the data classes: © equals() - The equals() function returns true if two objects have the identical contents. It operates similarly to "==," although for Float and Double values it works differently. © hashCode() - The hashCode() function returns the object's hashcode value. * copy() - The copy() function is used to duplicate an object, changing only a few of its characteristics while leaving the rest unaltered. © toString() - This function returns a string containing all of the data class's parameters. To ensure consistency, data classes must meet the following requirements: At least one parameter is required for the primary constructor. val or var must be used for all primary constructor parameters. Abstract, open, sealed, or inner data classes are not possible. Only interfaces may be implemented by data classes. Example: Page © Copyright by Interviewbitom ran tysid Kotlin Interview Questions data class Sample(var input1 : Int, var input2 : Int) The above code snippet creates a data class Sample with two parameters. fun main(agrs: Array
) { val temp = Sample(1, 2) print1n(temp) Here, we create an instance of the data class Sample and pass the parameters to it. Output:- Sample(input1=1, input2=2) 4. Explain the concept of null safety in Kotlin. Kotlin's type system aims to eradicate null references from the code. If a program throws NullPointerExceptions at runtime it might result in application failure or system crashes. If the Kotlin compiler finds a null reference it throws a NullPointerException. Null Safety in Kotlin 2 InterviewBit Page 10 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions The Kotlin type system distinguishes between references that can hold null (nullable references) and those that cannot (non-null references). Null cannot be stored ina String variable. We get a compiler error if we try to assign null to the variable. var a: String = "intervien" a= null // results in compilation error If we want the above string to be able to hold null value as well, we can declare it of type nullable using the ‘?’ operator after the String keyword as follows : var a: String? = "interview" a = null // no compilation error Kotlin provides Safe Call (?.), Elvis (?:) and Not Null Assertion (!!) operators which define what needs to be done in case of a null encounter. This makes the code more reliable and less prone to errors. Thus, Kotlin enforces null safety by having nullable, non-nullable type variables and the different operators to tackle null encounters. 5. Explain Safe call, Elvis and Not Null Assertion operator in the context of Kotlin. Safe Call operator ( ?. ) - Null comparisons are trivial, but the number of nested if- else expressions can be exhausting. So, in Kotlin, there's a Safe call operator,?, that simplifies things by only doing an action when a specified reference holds a non-null value. It allows us to use a single expression to perform both a null check and a method call. Page 11 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions foo != null fo0.bar() foo == null null 2s InterviewSit For example, The following expression in Kotlin name? . toLowerCase() is equivalent to the following if(name != null) ame. toLowerCase( ) Elvis Operator ( ?: ) - When the original variable is null, the Elvis operator is used to return a non-null value or a default value. In other words, the elvis operator returns the left expression if it is not null, otherwise, it yields the right expression. Only if the left-hand side expression is null is the right-hand side evaluated. Page 12 © Copyright by Interviewbitrs a coco cla sI8 Kotlin Interview Questions The Elvis operator in action val result = value1 ?: value2 Leo NOT NULL, result is assigned its value 2s InterviewBit For example, The following expression in Kotlin val samplei = sample2 ?: "Undefined" is equivalent to the following val sample1 = if(sample2 != null) "Undefined" is NULL, results assigned value2's value Furthermore, on the right side of the Elvis operator, we may use throw and return expressions, which is particularly handy in functions. As a result, instead of returning a default value on the right side of the Elvis operator, we can throw an exception. For example, val sample1 = sample2 7: throw IllegalArgumentException("Invalid") Page 13 © Copyright by InterviewbitKotlin Interview Questions rs a coco cla sI8 Not Null Assertion Operator ( !! ) - If the value is null, the not null assertion (!!) operator changes it to a non-null type and throws an exception. Anyone who wants a NullPointerException can ask for it explicitly with this operator. For example, 71 KOTLIN fun main(args: Array
) { var sample : String? = null str!! length } The above code snippet gives the following output:- Exception in thread "main" kotLin.kotlinNullPointerException 6. Differentiate between Kotlin and Java. Bs InterviewBit Following are the differences between Kotlin and Java:- Page 14 © Copyright by Interviewbitx arn coco cla sI8 Doan est Basis Null Safety Kotlin By default, all sorts of variables in Kotlin are non-nullable (that is, we can't assign null values to any variables or objects). Kotlin code will fail to build if we try to assign or return null values. If we absolutely want a null value fora variable, we can declare it as follows: value num: Int? = null Java NullPointerExceptions are a big source of annoyance for Java developers. Users can assign null to any variable, however, when accessing an object reference with anull value, a null pointer exception is thrown, which the user must manage. Page 15 © Copyright by InterviewbitDoan est rs a coco cla sI8 7. What are the different types of constructors available in Kotlin? Explain them with proper examples. There are two types of Kotlin constructors: Primary ‘Secondary Constructor | Constructor 28s Interviewsit © Primary Constructor - This type of constructor is initialised in the class header and is provided after the class name. It is declared using the “constructor” keyword. Parameters are optional in this type of constructor. For example, class Sample constructor(val a: Int, val b: Int) { 71 code } If no annotations or access modifiers are provided, the constructor keyword can be omitted. The initialization code can be placed in a separate initializer block prefixed with the init keyword because the primary constructor cannot contain any code. For example, Page 16 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions 77 KOTLIN fun main(args: Array
) { val s1 = Sample(1, 2) brass Sanple(a : Int , b: Int) { val p: Int var qi Int // initializer block init { printin("The first parameter value is ; $p" printin("The second parameter value is : Sq") Output:- The first parameter value is: 1 The second parameter value is: 2 Explanation - The values 1 and 2 are supplied to the constructor arguments a and b when the object s1 is created for the class Sample. In the class p and q, two attributes are specified. The initializer block is called when an object is created, and it not only sets up the attributes but also prints them to the standard output. © Secondary Constructor - Secondary constructors allow for the initialization of variables as well as the addition of logic to the class. They have the constructor keyword prefixed to them. For example, 71 KOTLIN fun main(args: Array
) { val si = Sample(1, 2) } class Sample { constructor(a: Int, b: Int) { printin("The first parameter value is println("The second parameter value is : Page 17 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Output:- The first parameter value is: 1 The second parameter value is: 2 The compiler determines which secondary constructor will be called based on the inputs provided. We don't specify which constructor to use in the above program, so the compiler chooses for us. In Kotlin, a class can contain one or more secondary constructors and at most one primary constructor. The primary constructor initializes the class, while the secondary constructor initialises the class and adds some additional logic. 8. Explain the various methods to iterate over any data structure in Kotlin with examples. Following are the different ways to iterate over any data structure in Kotlin : © For Loop- The for loop is used to scan any data structure that supplies an iterator in this case. It is not used in the same way as the for loop in other programming languages such as Java or C. In Kotlin, the for loop has the following Syntax: for(item in collection) { 7 code + Here, collection refers to the data structure to be iterated and item refers to each element of the data structure. For example, Page 18 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions 77 KOTLIN fun main(args: Array
) { var numbersArray = arrayOf(1,2,3,4,5,6,7,8,9,1) for (num in numbersarray){ if (num % 2 print("snum ") } } Output - 246810 © While Loop - It is made up of a code block and a condition to be checked for each iteration. First, the while condition is assessed, and if it is true, the code within the block is executed. Because the condition is verified every time before entering the block, it repeats until the condition turns false. The while loop can be thought of as a series of if statements that are repeated. The while loop's syntax is as follows: while(condition) { // code 3 For example, 7/ KOTLIN fun main(args: Array
) { var number = 1 while(number <= 5) { print1n(number) number++; } Output - Page 19 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions 1 2 3 4 5 Do While Loop - The condition is assessed after all of the statements inside the block have been executed. If the do-while condition is true, the code block is re- executed. As long as the expression evaluates to true, the code block execution procedure is repeated. The loop ends if the expression becomes false, and control is passed to the sentence following the do-while loop. Because it verifies the condition after the block is executed, it's also known as a post-test loop. The do-while loop's syntax is as follows: { // code { while(condition) For example, // KOTLIN fun main(args: Array
) { var number = 4 var sum = © do { ‘sum += number number -- }while(number > 0) print1n("Sum of first four natural numbers is $sum") Output - Sum of first four natural numbers is 10 9. How can you concatenate two strings in Kotlin? Page 20 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Following are the different ways by which we can concatenate two strings in Kotlin: Ast sting 2nd sting “This is string one” “This is string two” After concatenation the string is 2s InterviewBit Using String Interpolation:- We use the technique of string interpolation to concatenate the two strings. Basically, we substitute the strings in place of their placeholders in the initialisation of the third string. nterview" it” 's1 $82" // stores "Interview Bit" Using the + or plus() operator:- We use the ‘+’ operator to concatenate the two strings and store them in a third variable. s1 + s2 // stores "InterviewBit" si.plus(s2) // stores "Interviewsit" Using StringBuilder:- We concatenate two strings using the StringBuilder object. First, we append the first string and then the second string. Page 21 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions val si = "Interview" val s2 = "Bit" val s3 = StringBuilder() s3.append(s1).append(s2) val s4 = s3.toString() // stores “InterviewBit" 10. What do you understand about function extension in the context of Kotlin? Explain. In Kotlin, we can add or delete method functionality using extensions, even without inheriting or altering them. Extensions are statistically resolved. It provides a callable function that may be invoked with a dot operation, rather than altering the existing class. KOTLIN EXTENSION FUNCTION Bs nterviewSit Function Extension - Kotlin allows users to specify a method outside of the main class via function extension. We'll see how the extension is implemented at the functional level in the following example: Page 22 © Copyright by Interviewbitrs a coco cla sI8 Kotlin Interview Questions 7 KOTLIN class Sample { var str ; String = "null" fun printstr() { print(str) 3 fun main(args: Array
) { var ‘O var c = Sample() c.str = a.add(b) c.printstr() 7/ function extension fun Sample.add(a : Sample):String{ var temp = Sample() temp.str = this.str +" " 4a.str return temp.str Output: Interview Bit Explanation:- We don't have a method named "addStr" inside the "Sample" class in the preceding example, but we are implementing the same method outside of the class. This is all because of function extension. 11. What do you understand about Companion Object in the context of Kotlin? Page 23 © Copyright by InterviewbitKotlin Interview Questions rs a coco cla sI8 In some languages, such as Java, the static keyword is used to declare class members and utilise them without creating an object, i.e. by simply calling them by their class name. In Kotlin, there is nothing called the “static” keyword. So, if we want to achieve the functionality of static member functions, we use the companion objects. This is also referred to as Object Extension. Companion Object P ZA uu Bs InterviewBit We must use the companion keyword in front of the object definition to construct a companion object. // syntax in KOTLIN class CompanionClass { companion object CompaniondbjectName { 17 code } } Val obj = CompanionClass .companionobjectName We can also remove the CompanionObject name and replace it with the term companion, resulting in the companion object's default name being Companion, as shown below: Page 24 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions 71 KOTLIN class CompanionClass { companion object { // code + } val obj = CompanionClass.Companion All the required static member functions and member variables can be kept inside the companion object created. For example, class Sample { companion object Test { var a: Int =41 fun testFunction() = print1n("Companion Object’s Member function called.") } 3 fun main(args: Array
) { print1n(Sample.a) Sample. testFunction() Output:- 1 Companion Object’s Member function called. 12. Differentiate between open and public keywords in Kotlin. The keyword “open” refers to the term "open for expansion". The open annotation on aclass is the polar opposite of the final annotation in Java: it allows others to inherit from it. By default, a class cannot be inherited in Kotlin. In Kotlin, an open method signifies that it can be overridden, whereas it cannot be by default. Instead, any methods in Java can be overridden by default. In Kotlin, all the classes are public by default. If no visibility modifier is specified, public is used by default, which means our declarations will be accessible everywhere inside the program. 13. Explain about the “when” keyword in the context of Kotlin. Page 25 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions The “when” keyword is used in Kotlin to substitute the switch operator in other languages such as Java. When a certain condition is met, a specific block of code must be run. Inside the when expression, it compares all of the branches one by one until a match is discovered. After finding the first match, it proceeds to the conclusion of the when block and executes the code immediately following the when block. We do not need a break statement at the end of each case, unlike switch cases in Java or any other programming language. Replace “switch” with “when” ABs Interviewsit For example, J/ KOTLIN fun main(args: Array
) { var temp = "Interview" when(temp) { "Interview" -> printn("Interview Bit is the solution.") "Job" -> println("Interview is the solution.") "Success" -> println("Hard Work is the solution.") } 3 Output:- Page 26 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Interview Bit is the solution. Explanation:- In the above code, the variable temp has the value “Interview”. The when condition matches for the exact value as that of temp’s and executes the corresponding code statements. Thus, “Interview Bit is the solution” is printed. 14. What are the advantages of Kotlin over Java? Following are the advantages of Kotlin over Java:- Advantages of Kotlin over Java 6 << = = Java > InterviewBit Page 27 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Data class: In Java, you must create getters and setters for each object, as well as properly write hashCode (or allow the IDE to build it for you, which you must do every time you update the class), toString, and equals. Alternatively, you could utilize lombok, but that has its own set of issues. In Kotlin, data classes take care of everything. Patterns of getter and setter: In Java, for each variable, you use it for, rewrite the getter and setter methods. You don't have to write getter and setter in kotlin, and if you must, custom getter and setter take a lot less typing. There are additional delegates for identical getters and setters. Extension Functions: In Java, there is no support for extension functions. Kotlin on the other hand provides support for extension functions which makes the code more clear and cleaner. Support for one common codebase: You may extract one common codebase that will target all of them at the same time using the Kotlin Multi-Platform framework. Support for Null Safety: Kotlin has built-in null safety support, which is a lifesaver, especially on Android, which is full of old Java-style APIs. Less prone to errors: There is less space for error because it is more concise and expressive than Java. Kotlin Interview Questions for Experienced 15. Which one is better to use - val mutableList or var immutableList in the context of Kotlin? The program's design clarity is improved by using mutable and immutable lists. This is done to have the developer think about and clarify the collection's purpose. We use a mutable list if the collection will alter as part of the design. On the other hand, we use an immutable list if the model is only meant to be viewed. Page 28 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Val and var serve a distinct purpose than immutable and mutable lists. The val and var keywords specify how a variable's value/reference should be handled. We use var when the value or reference of a variable can be altered at any moment. On the other hand, we use val when a variable's value/reference can only be assigned once and cannot be modified later in the execution. Immutable lists are frequently preferred for a variety of reasons: © They promote functional programming, in which state is passed on to the next function, which constructs a new state based on it, rather than being altered. This is evident in Kotlin collection methods like map, filter, reduce, and so forth. © It's often easier to understand and debug software that doesn't have any side effects (you can be sure that the value of an object will always be the one at its definition). © Because no write access is required in multi-threaded systems, immutable resources cannot induce race conditions. However, there are some disadvantages of using immutable lists as well. They are as follows: © Copying large collections simply to add/remove a single piece is very expensive. © When you need to alter single fields frequently, immutability can make the code more difficult. Data classes in Kotlin provide a built-in copy() method that allows you to clone an instance while changing only part of the fields' values. 16. What do you understand about lateinit in Kotlin? When would you consider using it? Page 29 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions KOTLIN LATEINIT 5 Interviewsit lateinit is an abbreviation for late initiation.If you don't want to initialize a variable in the constructor and instead want to do it later, and you can guarantee the initialization before using it, use the lateinit keyword to declare that variable. It won't start allocating memory until it's been initialized. Lateinit cannot be used for primitive type attributes like Int, Long, and so on. Because the lateinit variable will be initialized later, you cannot use val. When a lateinit property is accessed before it has been initialized, a special exception is thrown that explicitly identifies the property and the fact that it hasn't been initialized. For example, 77 KOTLIN lateinit var test: string fun testFunction() { test = "Interview" println("The length of string is "+test.length) test = "Bit" When the testFunction is called, we get the following output:- There are a few scenarios in which this is particularly useful, for example: Page 30 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Variables that are initialized in lifecycle methods in Android; Using Dagger for DI: injected class variables are initialized outside of the constructor and independently; Setup for unit tests: in a @Before - annotated function, test environment variables are initialized; Annotations in Spring Boot (for example, @Autowired). 17. Explain lazy initialization in the context of Kotlin. There are some classes whose object initialization is so time-consuming that it causes the entire class creation process to be delayed. Lazy initialisation helps in such problems. When we declare an object using lazy initialisation, the object is initialised only once when the object is used. If the object is not used throughout, the object is not initialised. This makes the code more efficient and faster. For example, let us imagine you have a SlowClass class and you require an object of that SlowClass in a different class called FastClass: 71 KOTLIN class FastClass { private val slowbject: SlowClass = SlowClass() We are generating a large object here, which will cause the development of the FastClass to be slow or delayed. There may be times where the SlowClass object isn't required. As a result, the lazy keyword can assist you in this situation: class FastClass { private val slowObject: SlowClass by lazy { SlowClass() } For example, Page 31, © Copyright by Interviewbitom ran tysid Kotlin Interview Questions 77 KOTLIN class FastClass { private val slow0bject: SlowClass by lazy { println("Slow Object initialised") SlowClass() fun access() { println(slowobject ) 3 fun main(args: Array
) { val fastClass = FastClass() print1n("FastClass initialised") fastClass.access() fastClass. access() 3 Output:- FastClass initialised Slow Object initialised SlowClass@2b12Fkk7 SlowClass@2b12Fkk7 Explanation:- In the above code, we have instantiated an object of the SlowClass inside the class structure of the FastClass using lazy initialisation. The object of the SlowClass is generated only when it is accessed in the above code, that is, when we call the access() method of the FastClass object and the same object is present throughout the main() method. 18. Differentiate between latei Explain the cases when you should use latei you should use lazy initialisation. it and lazy initialisation. it and when Following are the differences between lateinit and lazy initialisation:- Page 32 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Learn Kotlin: lateinit vs lazy > Interviewsit Page 33, © Copyright by Interviewbitx arn coco cla sI8 Pace ety lateinit The main purpose is to delay the initialisation toa later point in time. It's possible to initialise the object from anywhere in the program. Multiple initializations are possible in this case. It's not thread- safe. In a multi- threaded system, itis up to the user to correctly initialise. It works only with var. The islnitialized method is added to verify if the value has previously been initialised. Properties of lazy initialisation The main purpose is to initialise an object only when it is used at a later point in time. Also, a single copy of the object is maintained throughout the program. Only the initializer lambda can be used to initialise it. Only a single initialisation is possible in this case. Thread-safety is enabled by default, ensuring that the initializer is only called once. It works only with val. It is impossible to uninitialize a property. Page 34 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions There are a few easy principles to follow when deciding whether to use lateinit or lazy initialisation for property initialization: © Use latelnit if properties are mutable (i.e., they may change later). © Use lateinit if properties are set externally (for example, if you need to pass in an external variable to set it). There is still a way to use lazy, but it isn't’as obvious. © If they're only meant to be initialised once and shared by everybody, and they're more internally set (depending on a class variable), then lazyis the way to go. We could still use lateinit in a tactical sense, but utilising lazy initialisation would better encapsulate our initialization code. 19. What do you understand about coroutines in the context of Kotlin? Kotlin Coroutines 2% InterviewBit Unlike many other languages with equivalent capabilities, async and await are neither keywords nor part of Kotlin's standard library. JetBrains’ kotlinx.coroutines library is a comprehensive library for coroutines. It includes a number of high-level coroutine-enabled primitives, such as launch and async. Kotlin Coroutines provide an API for writing asynchronous code in a sequential manner. Page 35, © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Coroutines are similar to thin threads. Coroutines are lightweight since they don't allocate new threads when they're created. Instead, they employ pre-defined thread pools as well as intelligent scheduling. The process of deciding which piece of work you will do next is known as scheduling. Coroutines can also be paused and resumed in the middle of their execution. This means you can have a long-term project that you can work on incrementally. You can pause it as many times as you want and continue it whenever you're ready. 20. Explain scope functions in the context of Kotlin. What are the different types of Scope functions available in Kotlin? The Kotlin standard library includes numerous functions that aid in the execution of a block of code within the context of an object. When you use a lambda expression to call these functions on an object, temporary scope is created. These functions are referred to as Scope functions. The object of these functions can be accessed without knowing its name. Scope functions make code more clear, legible, and succinct, which are key qualities of the Kotlin programming language. Scope Functions with vs. apply vs. also vs. let vs. run All you need to know 2 InterviewBit K Following are the different types of Scope functions available in Kotlin:- Page 36 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions 21. let:- Context object: it Return value: lambda result The let function is frequently used for null safety calls. For null safety, use the safe call operator(?.) with ‘let’. It only runs the block with a non-null value. apply:- Context object: this Return value: context object “Apply these to the object,” as the name suggests. It can be used to operate on receiver object members, primarily to initialise them. witl Context object: this Return value: lambda result When calling functions on context objects without supplying the lambda result, ‘with' is recommended. run:- Context object: this Return value: lambda result The ‘run’ function is a combination of the ‘let' and ‘with' functions. When the object lambda involves both initialization and computation of the return value, this is the method to use. We can use run to make null safety calls as well as other calculations. also:- Context object: it Return value: context object It's used when we need to do additional operations after the object members have been initialised. Explain suspend function in the context of Kotlin. Page 37 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions A function that may be started, halted, then resumed is known as a suspend function. One of the most important things to remember about the suspend functions is that they can only be invoked from another suspend function or from a coroutine. Suspending functions are merely standard Kotlin functions with the suspend modifier added, indicating that they can suspend coroutine execution without blocking the current thread. This means that the code you're looking at may pause execution when it calls a suspending function and restart execution ata later time. However, it makes no mention of what will happen to the present thread in the meantime. function, function, , functionB AB InterviewBit Suspending functions can call any other ordinary functions, but another suspending function is required to suspend the execution. Because a suspending function cannot be called from a regular function, numerous coroutine builders are supplied, allowing you to call a suspending function from a non-suspending scope like launch, async, or runBlocking. delay() function is an example of suspend function. 22. What do you understand about sealed classes in Kotlin? Page 38, © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Kotlin introduces a crucial new form of class that isn't seen in Java. These are referred to as "sealed classes." Sealed classes, as the name implies, adhere to constrained or bounded class hierarchies. A sealed class is one that has a set of subclasses. When it is known ahead of time that a type will conform to one of the subclass types, it is employed. Type safety (that is, the compiler will validate types during compilation and throw an exception if a wrong type has been assigned to a variable) is ensured through sealed classes, which limit the types that can be matched at compile time rather than runtime. KOTLIN SEALED CLASSES £82. Interviewsit The syntax is as follows:- sealed class className Another distinguishing aspect of sealed classes is that their constructors are by default private. Due to the fact that a sealed class is automatically abstract, it cannot be instantiated. For example, Page 39 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions // KOTLIN sealed class Sample { class A : Sample() { fun print() printin(""This is the subclass A of sealed class Sample") 3 class B : Sample() { fun print() printin("This is the subclass 8 of sealed class Sample") } fun main() { val obj1 = Sample.B() obji.print() val_obj2 = Sample.a() obj2.print() Output: This is the subclass B of sealed class Sample This is the subclass A of sealed class Sample Explanation:- In the above code, we have created a sealed class named “Sample” and we have created two sub classes within it named “A” and “B”. In the main function, we create an instance of both the sub classes and call their “print” method. 23. What do you understand about the backing field in Kotlin? A backing field is an auto-generated field for any property that may only be used inside accessors (getter or setter) and will only be present if it utilizes the default implementation of at least one of the accessors, or if a custom accessor refers to it through the field identifier. This backing field is used to avoid an accessor's recursive call, which would result in a StackOverflowError. Page 40 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions Fields are not allowed in Kotlin classes. When employing custom accessors, however, it is occasionally required to have a backing field. Kotlin includes an automatic backing field for these purposes, which may be accessed by the field identifier. For example, var marks: Int = someValue get() = field set(value) { Field = value Explanation:- Here the field identifier actsas a reference to the property “marks” value in the get() and set() method. So, whenever we call the get(), we get the field’s value returned. Similarly, whenever we call the set(), we set the “marks” property value to “value”. 24. Differentiate between launch / join and async / await in Kotlin. launch / join:- The launch command is used to start and stop a coroutine. It's as though a new thread has been started. If the code inside the launch throws an exception, it's considered as an uncaught exception in a thread, which is typically written to stderr in backend JVM programs and crashes Android applications. Join is used to wait for the launched coroutine to complete before propagating its exception. A crashed child coroutine, on the other hand, cancels its parent with the matching exception. async / await:- The async keyword is used to initiate a coroutine that computes a result. You must use await on the result, which is represented by an instance of Deferred. Uncaught exceptions in async code are held in the resultant Deferred and are not transmitted anywhere else. They are not executed until processed. 25. What are some of the disadvantages of Kotlin? Following are some of the disadvantages of Kotlin: Page 41 © Copyright by Interviewbitom ran tysid Kotlin Interview Questions KOTLIN DISADVANTAGE Bs nterviewit In Kotlin, there are a few keywords that have non-obvious meanings: internal, crossinline, expect, reified, sealed, inner, open. Java has none of these. Checked exceptions are likewise absent in Kotlin. Although checked exceptions have become less prominent, many programmers believe them to be an effective technique to ensure that their code is stable. A ot of what happens in Kotlin is hidden. You can almost always trace the logic of a program in Java. When it comes to bug hunting, this can be really useful. If you define a data class in Kotlin, getters, setters, equality testing, tostring, and hashcode are automatically added for you. Learning resources are limited. The number of developers who are moving to Kotlin is growing, yet there is a small developer community accessible to help them understand the language or address problems during development. Kotlin has variable compilation speed. In some situations, Kotlin outperforms Java, particularly when executing incremental builds. However, we must remember that when it comes to clean builds, Java is the clear winner. Page 42 © Copyright by InterviewbitC Interview Questions Web Api Interview Questions Cpp Interview Questions Machine Learning Interview Questions Css Interview Questions Django Interview Questions Operating System Interview Questions Git Interview Questions Dbms Interview Questions PI Sql Interview Questions Ansible Interview Questions Php Interview Questions Hibernate Interview Questions Oops Interview Questions Docker Interview Questions Laravel Interview Questions Dot Net Interview Questions React Native Interview Questions Java 8 Interview Questions Spring Boot Interview Questions Tableau Interview Questions Java Interview Questions C Sharp Interview Questions Node Js Interview Questions Devops Interview Questions Mysql Interview Questions Asp Net Interview Questions Kubernetes Interview Questions ‘Aws Interview Questions Mongodb Interview Questions Power Bi Interview Questions Linux Interview Questions Jenkins Interview Questions Page 43 © Copyright by Interviewbit
You might also like
Accounting Made Simple (PDFDrive)
PDF
No ratings yet
Accounting Made Simple (PDFDrive)
196 pages
Unit 1-1
PDF
100% (1)
Unit 1-1
22 pages
Sample Paper-CAIIB-ABM-By Dr. Murugan
PDF
No ratings yet
Sample Paper-CAIIB-ABM-By Dr. Murugan
134 pages
Moskala M. Functional Kotlin 2023
PDF
No ratings yet
Moskala M. Functional Kotlin 2023
258 pages
Unit 1
PDF
No ratings yet
Unit 1
18 pages
Kotlin Reference
PDF
No ratings yet
Kotlin Reference
1,560 pages
Network Analysis (Gate Bits) PDF
PDF
No ratings yet
Network Analysis (Gate Bits) PDF
90 pages
Sample Paper-CAIIB-ABFM-By Dr. Murugan
PDF
0% (1)
Sample Paper-CAIIB-ABFM-By Dr. Murugan
92 pages
Wipro - Main Price List 15th May 2022
PDF
No ratings yet
Wipro - Main Price List 15th May 2022
88 pages
Unit 1 Introduction To Android and Kotlin
PDF
No ratings yet
Unit 1 Introduction To Android and Kotlin
79 pages
Kotlin Spring
PDF
No ratings yet
Kotlin Spring
88 pages
Let's Learn Kotlin
PDF
100% (1)
Let's Learn Kotlin
21 pages
Kotlin Android
PDF
No ratings yet
Kotlin Android
56 pages
Vedicmaths Ebook
PDF
100% (9)
Vedicmaths Ebook
212 pages
Kotlin Quick Reference
PDF
100% (1)
Kotlin Quick Reference
136 pages
AADK Answers
PDF
100% (1)
AADK Answers
39 pages
Kotlin For Beginners Guide
PDF
No ratings yet
Kotlin For Beginners Guide
122 pages
Kotlin Interview Questions and Answers
PDF
No ratings yet
Kotlin Interview Questions and Answers
9 pages
Kotlin First Program Concept
PDF
No ratings yet
Kotlin First Program Concept
250 pages
Kotlin Tutorial PDF
PDF
100% (1)
Kotlin Tutorial PDF
5 pages
Kotlin PDF
PDF
No ratings yet
Kotlin PDF
20 pages
Kotlin Interview Questions
PDF
100% (1)
Kotlin Interview Questions
44 pages
Kotlin Tutorial
PDF
No ratings yet
Kotlin Tutorial
24 pages
Kotlin Part 1 Français
PDF
No ratings yet
Kotlin Part 1 Français
105 pages
Single Track PDF
PDF
No ratings yet
Single Track PDF
88 pages
02 - Basic Kotlin
PDF
No ratings yet
02 - Basic Kotlin
36 pages
U1-MAD With Kotlin
PDF
No ratings yet
U1-MAD With Kotlin
56 pages
Lecture 1- Kotlin Programming Language Introduction - ١١٠٠١٨ - 065349
PDF
No ratings yet
Lecture 1- Kotlin Programming Language Introduction - ١١٠٠١٨ - 065349
75 pages
Shimelis Atile PDF
PDF
No ratings yet
Shimelis Atile PDF
116 pages
Shimelis Atile PDF
PDF
No ratings yet
Shimelis Atile PDF
116 pages
Lesson 1 Kotlin Basics
PDF
No ratings yet
Lesson 1 Kotlin Basics
59 pages
Kotlin Language Documentation 2.1.0
PDF
No ratings yet
Kotlin Language Documentation 2.1.0
68 pages
Machines 1
PDF
No ratings yet
Machines 1
145 pages
DSC MUET Hello To Kotlin
PDF
No ratings yet
DSC MUET Hello To Kotlin
64 pages
Android
PDF
No ratings yet
Android
40 pages
MAD - Kotlin L2
PDF
No ratings yet
MAD - Kotlin L2
59 pages
501 02 CH 1
PDF
No ratings yet
501 02 CH 1
26 pages
Kolin Unit1
PDF
No ratings yet
Kolin Unit1
29 pages
Kotlin
PDF
No ratings yet
Kotlin
41 pages
Kotlin Docs
PDF
No ratings yet
Kotlin Docs
23 pages
Accounting Notes
PDF
No ratings yet
Accounting Notes
30 pages
Improve Your Memory
PDF
No ratings yet
Improve Your Memory
14 pages
Android App Development: Six Weeks Summer Training On
PDF
No ratings yet
Android App Development: Six Weeks Summer Training On
71 pages
Introduction of Kotlin Programing Language
PDF
No ratings yet
Introduction of Kotlin Programing Language
7 pages
5 Basic Kotlin Interview Questions With Answers
PDF
No ratings yet
5 Basic Kotlin Interview Questions With Answers
12 pages
Kotlin
PDF
No ratings yet
Kotlin
30 pages
Kotlin Vs Java - Which Is The Best Option For Android App Development?
PDF
No ratings yet
Kotlin Vs Java - Which Is The Best Option For Android App Development?
16 pages
Kotlin For Android: Ken Kousen, Kousen IT, Inc
PDF
No ratings yet
Kotlin For Android: Ken Kousen, Kousen IT, Inc
38 pages
Kai Koenig (@agentk) : Little Helpers For Android Development With Kotlin
PDF
No ratings yet
Kai Koenig (@agentk) : Little Helpers For Android Development With Kotlin
52 pages
Basic Kotlin 01
PDF
No ratings yet
Basic Kotlin 01
26 pages
Kotlin 100 Questiom
PDF
No ratings yet
Kotlin 100 Questiom
36 pages
What Is Kotlin
PDF
No ratings yet
What Is Kotlin
21 pages
Kotlin Cheat Sheet 1p - by Ekito 1.2
PDF
No ratings yet
Kotlin Cheat Sheet 1p - by Ekito 1.2
4 pages
AMC Q A Solved
PDF
No ratings yet
AMC Q A Solved
34 pages
Kotlin
PDF
No ratings yet
Kotlin
18 pages
Kotlin Tutorial For Beginners: Learn Kotlin Programming in 2 Hours
PDF
No ratings yet
Kotlin Tutorial For Beginners: Learn Kotlin Programming in 2 Hours
27 pages
Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass
PDF
No ratings yet
Exploring Basic Kotlin Syntax and Structure - Day 2 Android 14 Masterclass
20 pages
Tybca-501-02-Amc MCQ Bank
PDF
No ratings yet
Tybca-501-02-Amc MCQ Bank
13 pages
Kot Lin Notes
PDF
No ratings yet
Kot Lin Notes
8 pages
Kotlin Programming-Day2
PDF
No ratings yet
Kotlin Programming-Day2
14 pages
Corporate
PDF
No ratings yet
Corporate
16 pages
Advance Kotlin Assignment
PDF
No ratings yet
Advance Kotlin Assignment
10 pages
Advance Kotlin Assignment
PDF
No ratings yet
Advance Kotlin Assignment
10 pages
Kotlin Interview Questions
PDF
No ratings yet
Kotlin Interview Questions
8 pages
Kotlin Tutorial
PDF
No ratings yet
Kotlin Tutorial
7 pages
Normalization Methods Application1
PDF
No ratings yet
Normalization Methods Application1
8 pages
Kotlin Interview Cheat Sheet
PDF
No ratings yet
Kotlin Interview Cheat Sheet
9 pages
Final Cheat Sheet
PDF
No ratings yet
Final Cheat Sheet
6 pages
Kotlin
PDF
No ratings yet
Kotlin
4 pages
Ages PDF
PDF
No ratings yet
Ages PDF
8 pages
IT 64 - Questions
PDF
No ratings yet
IT 64 - Questions
3 pages
01-Notification 8 - TT With JD
PDF
No ratings yet
01-Notification 8 - TT With JD
3 pages
IS325testone (1) Answers
PDF
No ratings yet
IS325testone (1) Answers
2 pages
Kotlin Cheat Sheet by Ekito 1.2 2
PDF
No ratings yet
Kotlin Cheat Sheet by Ekito 1.2 2
2 pages