kotlin strings

Kotlin Tutorial – Learn Kotlin Programming Online

The Kotlin Tutorial explains both the fundamental and more complex Kotlin principles. It is intended for both beginners and experts to learn the Kotlin Tutorial online. The trend of naming programming languages after islands was started by Java, and it is carried on by Kotlin. Compared to many other programming languages, Kotlin is intended to be safer, simpler to comprehend and write, and both. The language, compiler, and related tools are entirely open source and free to use in accordance with the Apache 2 license.

Kotlin Tutorial for Beginners

What is Kotlin?

The primary goals of the Kotlin language are to make code safe and concise. A piece of code is frequently considered brief when it is easy to read and comprehend. Conciseness when writing code also contributes to its effectiveness and speed.

Kotlin has a number of safety-related features that make it more likely that potential problems may be discovered when the code is being written rather than leading to runtime crashes.

Java, which Sun Microsystems originally made available in 1995, is still by far the most popular programming language in use today. Up until the introduction of Kotlin, it’s probable that every Android app available on the market was made in Java. Since acquiring the Android operating system, Google has made considerable efforts in fine-tuning and improving the compilation and runtime environments for running Java-based code on Android-powered devices.


Kotlin Overview

Kotlin is a language by JetBrains, the company behind IntelliJ IDEA and other  tools, and is purpose built for large-scale software projects to improve upon Java with a focus on readability, correctness, and developer productivity.

In response to Java’s limitations, which were limiting the development of JetBrains’ software products, and after an evaluation found that none of the other JVM languages were suitable, the Kotlin language was created. Because its primary goal was to be utilized to better their products, Kotlin places a strong emphasis on interoperability with Java code and the Java standard library.

Kotlin Features 

The main focus on interoperability in the Kotlin language and runtime is its most important feature. Idiomatic Kotlin should be able to call Java and have Java call into Kotlin with ease, unlike other JVM alternatives. Scala is a good example of this. In actuality, you shouldn’t even be conscious of crossing the line. The runtime for Kotlin is highly condensed and only serves the language’s features.

We can identify some of the Kotlin features that are most valuable to Android and resolve particular, recurring issues that afflict client application development.

Kotlin Tutorial : Arrays

Generic arrays in Kotlin are represented by Array<T>.

To create an empty array, use emptyArray<T>() factory function:

val empty = emptyArray<String>()

To create an array with given size and initial values, use the constructor:

var strings = Array<String>(size = 5, init = { index -> "Item #$index" })
print(Arrays.toString(a)) // prints "[Item #0, Item #1, Item #2, Item #3, Item #4]"
print(a.size) // prints 5

Arrays have get(index: Int): T and set(index: Int, value: T) functions:

strings.set(2, "ChangedItem")
print(strings.get(2)) // prints "ChangedItem"
// You can use subscription as well:
strings[2] = "ChangedItem"
print(strings[2]) // prints "ChangedItem"

Kotlin -Arrays of Primitives

These types do not inherit from Array<T> to avoid boxing, however, they have the same attributes and methods.

       Kotlin type               Factory function                  JVM type

  • BooleanArray            booleanArrayOf(true, false)   boolean[]
  • ByteArray                   byteArrayOf(1, 2, 3)                 byte[]
  • CharArray                  charArrayOf(‘a’, ‘b’, ‘c’)            char[]
  • DoubleArray             doubleArrayOf(1.2, 5.0)           double[]
  • FloatArray                 floatArrayOf(1.2, 5.0)               float[]
  • IntArray                     intArrayOf(1, 2, 3)                     int[]
  • LongArray                 longArrayOf(1, 2, 3)                  long[]
  • ShortArray                shortArrayOf(1, 2, 3)                 short[]
Kotlin -Create Array
val a = arrayOf(1, 2, 3) // creates an Array<Int> of size 3 containing [1, 2, 3].
Kotlin -Create Array using Closure
val a = Array(3) { i -> i * 2 } // creates an Array<Int> of size 3 containing [0, 2, 4]
Kotlin – Create an uninitialized array
val a = arrayOfNulls<Int>(3) // creates an Array<Int?> of [null, null, null]

The returned array will always have a nullable type. Arrays of non-nullable items can’t be created uninitialized.

Kotlin Tutorial : Collections

Kotlin distinguishes between mutable and immutable collections (lists, sets, maps, etc.) in order to contrast with many other languages.

It’s helpful to have precise control over when collections can be updated when creating effective APIs and removing problems.

Collections using List

// Create a new read-only List<String>
val list = listOf("Item 1", "Item 2", "Item 3")
println(list) // prints "[Item 1, Item 2, Item 3]"

Collections using Map

// Create a new read-only Map<Integer, String>
val map = mapOf(Pair(1, "Item 1"), Pair(2, "Item 2"), Pair(3, "Item 3"))
println(map) // prints "{1=Item 1, 2=Item 2, 3=Item 3}"

Collections using Set

// Create a new read-only Set<String>
val set = setOf(1, 3, 5)
println(set) // prints "[1, 3, 5]"

Kotlin Tutorial : Functions

     Parameter           Details

  • Name                   Name of the function
  • Params                 Values given to the function with a name and type: Name:Type
  • Type                      Return type of the function
  • Type Argument   Type parameter used in generic programming (not necessarily return type)
  • ArgName              Name of value given to the function
  • ArgType               Type specifier for ArgName
  • ArgNames           List of ArgName separated by commas

Basic Functions

Functions are declared with the fun keyword, which is then followed by the function name and any associated parameters. It is also possible to specify a function’s return type, which is Unit by default. The body of the function is surrounded by braces. If the return type is something other than Unit, the body must emit a return statement for each ending branch.

fun sayMyName(name: String): String {
return "Your name is $name"
}

A shorthand version of the same:

fun sayMyName(name: String): String = "Your name is $name"

And the type can be omitted since it can be inferred:

fun sayMyName(name: String) = "Your name is $name"

Inline Functions

Function declarations can be made inline by using the inline prefix. In this situation, they operate similarly to C macros and are replaced at compilation time by the function’s body code rather than being called. When lambdas are used as function parameters, this occasionally leads to enhanced performance.

inline fun sayMyName(name: String) = "Your name is $name"

One difference from C macros is that inline functions can’t access the scope from which they’re called:

inline fun sayMyName() = "Your name is $name"
fun main() {
val name = "Foo"
sayMyName() # => Unresolved reference: name
}

Lambda Functions

Lambda functions, which act as function parameters, are anonymous functions that are typically formed during a function call. If arguments are required, they should be placed before the arrow ->. They are stated by enclosing expressions in braces.

{ name: String ->
"Your name is $name" //This is returned
}

The last statement inside a lambda function is automatically the return value.

The type’s are optional, if you put the lambda on a place where the compiler can infer the types.

Multiple arguments:

{ argumentOne:String, argumentTwo:String ->
"$argumentOne - $argumentTwo"
}

If the lambda function only needs one argument, then the argument list can be omitted and the single argument be referred to using it instead.

{ "Your name is $it" }

If the only argument to a function is a lambda function, then parentheses can be completely omitted from the function call.

# These are identical
listOf(1, 2, 3, 4).map { it + 2 }
listOf(1, 2, 3, 4).map({ it + 2 })

Operator Functions

Kotlin-only implementations are possible for a predetermined set of operators with fixed symbolic representation (like + or *) and fixed precedence.

To implement an operator, we provide a member function or an extension function with a fixed name for the corresponding type. Functions that overload operators must be identified using the operator modifier.

data class IntListWrapper (val wrapped: List<Int>) {
operator fun get(position: Int): Int = wrapped[position]
}
val a = IntListWrapper(listOf(1, 2, 3))
a[1] // == 2

 

Online Training Tutorials

  • ABAP ModularizationABAP Modularization an Overview What is ABAP Modularization and its benefits? If the program contains the same or similar blocks of statements or it is required to process the same function several times, we can avoid […]
  • user exitsWhat is the usage of User Exits in SAP SD?User exits are routines which SAP allows you to add in additional customized programs process without affecting the standard SAP programs. SAP user exits are usually declared as a form […]
  • Perl Interview Questions and AnswersPerl Interview Questions and AnswersWe have listed of Perl Interview Questions and Answers that have been designed for Perl professionals who are preparing interviews on Perl Programming. Perl is sometimes called the […]
  • SAP FI (Financial Accounting) ModuleSAP FI (Financial Accounting) Module TrainingThe SAP FI module (Financial Accounting) is designed to capture organizations business transactions in a manner that will satisfy external reporting requirements. Local legal […]
  • VBScript Interview Questions and AnswersVBScript Interview Questions and AnswersVBScript is a powerful but easy-to learn scripting language that you can use to perform a number of useful activities, including enhancing your web pages and automating repetitive or […]
  • servlets tutorialServlet Database AccessServlet Database Access : Data that is shared between Web components and is persistent between invocations of a J2EE application is usually maintained by a database. Web components use the […]
  • C Program to Find Total of Even IntegersC Program Nested For Loop with ExampleIn this post explain C program Nested For Loop with Example. Ready to execute code with clean output, in easy way with simple steps. A class of "N" students take an annual examination […]
  • Search engine optimizationSearch Algorithm in SEO – How it Works?What is SEO search algorithm? All of the parts of the search engine are important, but the search algorithm is the cog that makes everything works. It might be more accurate to say that […]