Skip to main content

Posts

Kotlin Continue Jump Structure

Kotlin continue Jump Structure Kotlin, continue statement is used to repeat the loop. It continues the current flow of the program and skips the remaining code at specified condition. The continue statement within a nested loop only affects the inner loop. For example for(..){     //body of for above if     if(checkCondition){         continue     }     //body of for below if } In the above example, for loop repeat its loop when if condition execute continue. The continue statement makes repetition of loop without executing the below code of if condition. Kotlin continue example fun main(args: Array ) {     for (i in 1..3) {         println("i = $i")         if (j == 2) {        ...

Kotlin Return and Jump

Kotlin Return and Jump There are three jump expressions in Kotlin. These jump expressions are used for control the flow of program execution. These jump structures are: break continue return Break Expression A break expression is used for terminate the nearest enclosing loop. It is almost used with if-else condition. For example: for(..){     //body of for     if(checkCondition){         break;     } } In the above example, for loop terminates its loop when if condition execute break expression. Kotlin break example: fun main(args: Array ) {     for (i in 1..5) {         if (i == 3) {             break         }     println(i)     } } Output...

Kotlin Do-While Loop

Kotlin do-while Loop The do-while loop is similar to while loop except one key difference. A do-while loop first execute the body of do block after that it check the condition of while. As a do block of do-while loop executed first before checking the condition, do-while loop execute at least once even the condition within while is false. The while statement of do-while loop end with ";" (semicolon). Syntax do{      //body of do block } while(condition); Example of do -while loop Let's see a simple example of do-while loop printing value 1 to 5. fun main(args: Array ){      var i = 1      do {           println(i)           i++      }      while (i<=5); }  Output: 1 2 3 4 5 Example of do -while loop even condition of while if false In this example do-while loop execute ...

Kotlin While Loop

Kotlin while Loop The while loop is used to iterate a part of program several time. Loop executed the block of code until the condition has true. Kotlin while loop is similar to Java while loop. Syntax while(condition){     //body of loop }  Example of while Loop Let's see a simple example of while loop printing value from 1 to 5.  fun main(args: Array ){     var i = 1     while (i<=5){          println(i)          i++          } } Output: 1 2 3 4 5 Kotlin Infinite while Loop The while loop executes a block of code to infinite times, if while condition remain true.  For example:     fun main(args: Array ){          while (true){                println("infinite l...

Kotlin For Loop

Kotlin for Loop Kotlin for loop is used to iterate a part of program several times. It iterates through arrays, ranges, collections, or anything that provides for iterate. Kotlin for loop is equivalent to the foreach loop in languages like C#. Syntax of for loop in Kotlin:   for (item in collection){     //body of loop     }       Iterate through array Let's see a simple example of iterating the elements of array.          fun main(args : Array ) {          val marks = arrayOf(80,85,60,90,70)          for(item in marks){                    println(item)          }       } Output: 80 85 60 90 70 If the body of for loop contains only one single line of statement, it is not necessa...

Kotlin When Expression

Kotlin when Expression Kotlin, when expression is a conditional expression which returns the value. Kotlin, when expression is replacement of switch statement. Kotlin, when expression works as a switch statement of other language (Java, C++, C). Using when as an Expression Let's see a simple example of when expression. fun main(args: Array ){ var number = 4 var numberProvided = when(number) {     1 -> "One"     2 -> "Two"     3 -> "Three"     4 -> "Four"     5 -> "Five"     else -> "invalid number"     }           println("You provide $numberProvided")         }  Output: You provide Four Using when Without Expression It is not mandatory to use when as an expression, it can be used as normally as it used...

Kotlin if Expression

Kotlin if Expression In Kotlin, if is an expression is which returns a value. It is used for control the flow of program structure. There is various type of if expression in Kotlin. if-else expression if-else if-else ladder expression nested if expression Traditional if Statement Syntax of traditional if statement if(condation){      //code statement } Syntax of traditional if else statement if(condation){      //code statement } else{      //code statement } Kotlin if-else Expression As if is an expression it is not used as standalone, it is used with if-else expression and the result of an if-else expression is assign into a variable.   Syntax of if-else expression val returnValue = if (condation) {      //code statement } else {      // code statement } println(returnValue) Kotlin if-else Expression Example Let's see an example of...

Kotlin Programming Language

Kotlin  Basics Kotlin Hello World Program Kotlin Variable Kotlin Data Type Kotlin Type Conversion Kotlin Operator Kotlin Standard Input/Output Kotlin Comment Kotlin  Control Flow Kotlin if Expression Kotlin When Expression Kotlin For Loop Kotlin While Loop Kotlin Do-While Loop Kotlin Return and Jump Kotlin Continue Jump Structure Kotlin  Function Kotlin Function Kotlin Recursion Function Kotlin For Loop Kotlin Default and Named Argument Kotlin Lambda Function Kotlin Higher order function Kotlin Inline Function

Kotlin Type Conversion

Kotlin Type Conversion Type conversion is a process in which one data type variable is converted into another data type. In Kotlin, implicit conversion of smaller data type into larger data type is not supported (as it supports in java). For example Int cannot be assigned into Long or Double. In Java int value1 = 10; long value2 = value1; //Valid code In Kotlin var value1 = 10 val value2: Long = value1 //Compile error, type mismatch However in Kotlin, conversion is done by explicit in which smaller data type is converted into larger data type and vice-versa. This is done by using helper function. var value1 = 10 val value2: Long = value1.toLong() The list of helper functions used for numeric conversion in Kotlin is given below: toByte() toShort() toInt() toLong() toFloat() toDouble() toChar() Kotlin Type Conversion Example Let see an example to convert from Int to Long. fun main(args : Array ) {      var value1 = 100  ...

Kotlin Data Type

Kotlin Data Type Data type (basic type) refers to type and size of data associated with variables and functions. Data type is used for declaration of memory location of variable which determines the features of data. In Kotlin, everything is an object, which means we can call member function and properties on any variable. Kotlin built in data type are categorized as following different categories: Number Character Boolean Array String Number Types Number types of data are those which hold only number type data variables. It is further categorized into different Integer and Floating point. Byte 8 bit -128 to 127 Short 16 bit -32768 to 32767 Int 32 bit -2,147,483,648 to 2,147,483,647 Long 64 bit -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807 Float 32 bit 1.40129846432481707e-45 to 3.40282346638528860e+38 Double 64 bit 4.94065645841246544e-324 to 1.79769313486231570e+308 Char 4 bit -128 to 127 val value1 = 'A' //or val value2: Char ...

Kotlin Variable

Kotlin Variable Variable refers to a memory location. It is used to store data. The data of variable can be changed and reused depending on condition or on information passed to the program. Variable Declaration Kotlin variable is declared using keyword var and val. var language ="Java" val salary = 30000 The difference between var and val is specified later on this page. Here, variable language is String type and variable salary is Int type. We don't require specifying the type of variable explicitly. Kotlin complier knows this by initilizer expression ("Java" is a String and 30000 is an Int value). This is called type inference in programming. We can also explicitly specify the type of variable while declaring it. var language: String ="Java" val salary: Int = 30000 It is not necessary to initialize variable at the time of its declaration. Variable can be initialized later on when the program is executed. var language: String...

Kotlin Hello World Program

Kotlin is a statically-typed, general-purpose programming language. It is widely used to develop android applications. Our Kotlin Tutorial includes all topics of Kotlin such as introduction, architecture, class, object, inheritance, interface, generics, delegation, functions, mixing Java and Kotlin, Java vs. Kotlin, etc. Kotlin is a general-purpose, statically typed, and open-source programming language. It runs on JVM and can be used anywhere Java is used today. It can be used to develop Android apps, server-side apps and much more. Kotlin was developed by JetBrains team. A project was started in 2010 to develop the language and officially, first released in February 2016. Kotlin was developed under the Apache 2.0 license. Kotlin First Program Concept Let's understand the concepts and keywords of Kotlin program 'Hello World.kt'. fun main(args: Array ) { println("Hello World!") } 1. The first line of program defines a function called main...

Kotlin Comment

Kotlin Comment Comments are the statements that are used for documentation purpose. Comments are ignored by compiler so that don't execute. We can also used it for providing information about the line of code. There are two types of comments in Kotlin.   Single line comment. Multi line comment.   Single line comment Single line comment is used for commenting single line of statement. It is done by using '//' (double slash). For example:   fun main(args: Array ) {      // this statement used for print      println("Hello World!") } Output Hello World! Multi line comment Multi line comment is used for commenting multiple line of statement. It is done by using /* */ (start with slash strict and end with star slash). For example: fun main(args: Array ) {      /* this statement      is used      for print */           println("Hel...

Kotlin Standard Input/Output

Kotlin Standard Input/Output Kotlin standard input output operations are performed to flow byte stream from input device (keyboard) to main memory and from main memory to output device (screen). Kotlin Output Kotlin output operation is performed using the standard methods print() and println(). Let's see an example:   fun main(args: Array ) {      println("Hello World!")      print("Welcome to Earth") } Output Hello World! Welcome to Earth The methods print() and println() are internally call System.out.print() and System.out.println() respectively. Difference between print() and println() methods: print(): print() method is used to print values provided inside the method "()". println(): println() method is used to print values provided inside the method "()" and moves cursor to the beginning of next line. Example fun main(args: Array ){ println(10) println("Welcome to Earth") ...

Kotlin If Expression

Kotlin if Expression In Kotlin, if is an expression is which returns a value. It is used for control the flow of program structure. There is various type of if expression in Kotlin. if-else expression if-else if-else ladder expression nested if expression Traditional if Statement Syntax of traditional if statement if(condation){      //code statement } Syntax of traditional if else statement if(condation){      //code statement } else{      //code statement } Kotlin if-else Expression As if is an expression it is not used as standalone, it is used with if-else expression and the result of an if-else expression is assign into a variable.   Syntax of if-else expression val returnValue = if (condation) {      //code statement } else {      // code statement }      println(returnValue) Kotlin if-else Expression Example Let's s...

Kotlin Operator

Kotlin Operator Operators are special characters which perform operation on operands (values or variable).There are various kind of operators available in Kotlin. Arithmetic operator Relation operator Assignment operator Unary operator Bitwise operation Logical operator Arithmetic Operator Arithmetic operators are used to perform basic mathematical operations such as addition (+), subtraction (-), multiplication (*), division (/) etc.   + Addition a+b a.plus(b) - Subtraction a-b a.minus(b) * Multiply a*b a.times(b) / Division a/b a.div(b) % Modulus a%b a.rem(b) Example of Arithmetic Operator fun main(args : Array ) {      var a=10;      var b=5;      println(a+b);      println(a-b);      println(a*b);      println(a/b);     println(a%b); } Relation Operator Relation operator shows the relation and compares between operands. Following are the d...

PYTHON MONGODB LIMIT

M ONGODB LIMIT Limit the Result To limit the result in MongoDB, we use the limit() method. The limit() method takes one parameter, a number defining how many documents to return. Limit the result to only return 5 documents: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myresult = mycol.find().limit(5) for x in myresult:   print(x) {'_id': ObjectId('6325d5001d9e9d4c027643b8'), 'name': 'Kartik'} {'_id': ObjectId('6325e1ef7e4337dbd6d8b9a1'), 'name': 'Kartik'} {'_id': ObjectId('6325e20d0bea1e2841fcdd06'), 'name': 'Kartik'} {'_id': ObjectId('6325e2381039de66af625c07'), 'name': 'Kartik'} {'_id': ObjectId('6325e26da4ef8259d33e1a33'), 'name': 'Kartik'}

PYTHON UPDATE COLLECTION

U PDATE COLLECTION Update Collection You can update a record, or document as it is called in MongoDB, by using the update_one() method. The first parameter of the update_one() method is a query object defining which document to update. Note: If the query finds more than one record, only the first occurrence is updated. The second parameter is an object defining the new values of the document. Change the address from "Valley" to "Canyon": import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": "Valley 345" } newvalues = { "$set": { "address": "Canyon 123" } } mycol.update_one(myquery, newvalues) #print "customers" after the update: for x in mycol.find():   print(x) Update Many To update all documents that meets the criteria of the query, use the update_...

PYTHON MONGODB DROP COLLECTION

M ONGODB DROP COLLECTION Delete Collection You can delete a table, or collection as it is called in MongoDB, by using the drop() method. Delete the "customers" collection: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] mycol.drop() The drop() method returns true if the collection was dropped successfully, and false if the collection does not exist.

PYTHON MONGODB DELETE

M ONGODB DELETE Delete Document To delete one document, we use the delete_one() method. The first parameter of the delete_one() method is a query object defining which document to delete. Note: If the query finds more than one document, only the first occurrence is deleted. Delete the document with the address "Mountain 21": import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol = mydb["customers"] myquery = { "address": "Mountain 21" } mycol.delete_one(myquery) Delete Many Documents To delete more than one document, use the delete_many() method. The first parameter of the delete_many() method is a query object defining which documents to delete. Delete all documents were the address starts with the letter S: import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mydb = myclient["mydatabase"] mycol =...