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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
val empty = emptyArray<String>()
val empty = emptyArray<String>()
val empty = emptyArray<String>()

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
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
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
strings.set(2, "ChangedItem")
print(strings.get(2)) // prints "ChangedItem"
strings.set(2, "ChangedItem") print(strings.get(2)) // prints "ChangedItem"
strings.set(2, "ChangedItem")
print(strings.get(2)) // prints "ChangedItem"
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// You can use subscription as well:
strings[2] = "ChangedItem"
print(strings[2]) // prints "ChangedItem"
// You can use subscription as well: strings[2] = "ChangedItem" print(strings[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
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
val a = arrayOf(1, 2, 3) // creates an Array<Int> of size 3 containing [1, 2, 3].
val a = arrayOf(1, 2, 3) // creates an Array<Int> of size 3 containing [1, 2, 3].
val a = arrayOf(1, 2, 3) // creates an Array<Int> of size 3 containing [1, 2, 3].
Kotlin -Create Array using Closure
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
val a = Array(3) { i -> i * 2 } // creates an Array<Int> of size 3 containing [0, 2, 4]
val a = Array(3) { i -> i * 2 } // creates an Array<Int> of size 3 containing [0, 2, 4]
val a = Array(3) { i -> i * 2 } // creates an Array<Int> of size 3 containing [0, 2, 4]
Kotlin – Create an uninitialized array
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
val a = arrayOfNulls<Int>(3) // creates an Array<Int?> of [null, null, null]
val a = arrayOfNulls<Int>(3) // creates an Array<Int?> of [null, null, null]
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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]"
// 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]"
// 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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// 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}"
// 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}"
// 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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
// Create a new read-only Set<String>
val set = setOf(1, 3, 5)
println(set) // prints "[1, 3, 5]"
// Create a new read-only Set<String> val set = setOf(1, 3, 5) println(set) // prints "[1, 3, 5]"
// 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun sayMyName(name: String): String {
return "Your name is $name"
}
fun sayMyName(name: String): String { return "Your name is $name" }
fun sayMyName(name: String): String {
return "Your name is $name"
}

A shorthand version of the same:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun sayMyName(name: String): String = "Your name is $name"
fun sayMyName(name: String): String = "Your name is $name"
fun sayMyName(name: String): String = "Your name is $name"

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
fun sayMyName(name: String) = "Your name is $name"
fun sayMyName(name: String) = "Your name is $name"
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
inline fun sayMyName(name: String) = "Your name is $name"
inline fun sayMyName(name: String) = "Your name is $name"
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
inline fun sayMyName() = "Your name is $name"
fun main() {
val name = "Foo"
sayMyName() # => Unresolved reference: name
}
inline fun sayMyName() = "Your name is $name" fun main() { val name = "Foo" sayMyName() # => Unresolved reference: name }
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{ name: String ->
"Your name is $name" //This is returned
}
{ name: String -> "Your name is $name" //This is returned }
{ 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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{ argumentOne:String, argumentTwo:String ->
"$argumentOne - $argumentTwo"
}
{ argumentOne:String, argumentTwo:String -> "$argumentOne - $argumentTwo" }
{ 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
{ "Your name is $it" }
{ "Your name is $it" }
{ "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.


Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# These are identical
listOf(1, 2, 3, 4).map { it + 2 }
listOf(1, 2, 3, 4).map({ it + 2 })
# These are identical listOf(1, 2, 3, 4).map { it + 2 } listOf(1, 2, 3, 4).map({ it + 2 })
# 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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
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
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