Self-study/Kotlin

[Kotlin] Basics

Munyoung 2024. 1. 12. 11:34

1. Entry point

fun main(){
	println("Hello World")
}
  • All programs need an entry point to be run which is the main fuction
  • when building for Android, we don't use the main function directly 
  • fun = function
  • main -> name of our function 
  • println -> overloaded function , we could pass in any type 

2. Variables

1) val 

fun main(){
	val name: String = "Jerry"
    val height: Int = 5
    val d: Double = 5.5
    val l: Long = 500L
    val f: Float = 2.3F
    val b: Boolean = true
    val s: String = "Hi!"
    val c: Char = 'g'
    
    println("$name is $height feet tall")
}
  • val (variable name): (variable type) = (variable value)
  • Every varibable type can be type Any because every Kotlin class has Any as a superclass. 
  • Kotlin can determine the type for us when we initialize a variable. 
val num = 5
num = 10

//이건 불가능!
  • Read only/ can only be assigned once!! 
  • good practice to use val everywhere unless you need to use var

2) var

var num = 5
num = 10
// 이건 가능
  • Mutable
  • Can be reassigned

3) Const

  • Const values are read only variables know before code execution -> better performance 
  • they are determined at compile time -> only define primitive types and strings as const 
  • anything besides primitives and strings may have runtime side effects

4) Null Safety 

val str: String? = null //Nullable
val str: String = "Good Morning" //Non null
  • Null safety was created to avoid null references 
  • can't assign null to a non null type 
val str: String? = null //Nullable
println(str.length) // 불가능
  • When we try to use a property ( length ) of a nullable type we get an error
val str: String? = null
println(str?.length)

//output: null 

val str: String!! = null
println(str!!.length) 

//Throws an exception
  • We have to use certain operators to protect us from a null exception

3. Strings 

1) string 

val name = "Good Morning"
println(name)
println(name.length) //12
println(name.uppercase()) //GOOD MORNING
println(name.lowercase()) //good morning
println(name.isEmpty) //false

//print character index of the string 
println(name[0])
println(name[5])
println(name[9])
// get out of bounds errors
println(name[13])
  • concatenate don't do
val name = "Jerry"
val height = 10

println(name + "is" + height + " feet tall")
  • instead, to use a String template you wrap your expression like so expression
println("$name is $height feet tall")
  • format method
val str = "%s is %s feet tall"
println(str.format("Alex", 4))
  • Multiline Strings : Pressing shift + " three times, then enter , will create a multiline
    string
  • trimIndent() is not needed but you may prefer it for formatting purposes
    • It removes a common minimal indent from each line
    • And also removes first and last line if they are blank
val str = """

""".trimIndent

 

2) string comparison

val name = "Jerry"
val name2 = "Sarah"

println(name == name2) //false
println(name.equals(name2)) //false
  • String referential equality : name === name2 
val name = "Jerry"
val name2 = "Sarah"

println(name == name2) //false
  • Notice that when we use on two different strings with the same value, it is true
  • This is because of the string pool memory, which is different the heap memory
val name = "Jerry"
val name2 = "Jerry"

println(name === name2) //true
  • It checks if there is already a value of that string in the string pool memory
  • If there is, then it points to that string in memory
  • So in the previous example, only one string is created in the heap
    memory
val name = "Jerry"
val name2 = String(name.toCharArray())

pritln(name === name2)
  • In this example, name2 is a new object created on the heap, so comparing their memory locations will return false

4. Arithmetic Operators

val num1 = 10
val num2 = 3

println(num1 + num2)
println(num1 - num2)
println(num1 * num2)
println(num1 / num2)
println(num1 % num2)

 

1) Math: to use math such as finding the square root we can use the kotlin.math package

val num1 = 14.2
val result = kotlin.math.sqrt(num1)

pritnln(result)
import Kotlin.math.*

val num1 = 14.2

println(round(result))
println(sqrt(result))
println(floor(result))

5. if-else statement 

  • In this example we are using an if..else statement using a few comparison and logical operators
val num1 = 5
val num2 = 7
val num3 = 4

if(num1 < num2 || num3 >= num1){
	println("True")
}else{
	println("False")
}
  • Here we are turning that same statement into an expression by providing a return value.
  • Whatever comes last in the expression is what is returned, so any other logic can go beforehand
val num1 = 5
val num2 = 7
val num3 = 4

if(num1 < num2 || num3 >= num1){
	println("sponge")
	"True"
}else{
	println("star")
	"False"
}
  • When the if expression only needs one line of code for each block, you don't need brackets which has a slightly cleaner look. 

6. When statement 

  • similar to switch statment 
val species = "W"

when(species) {
	"C" -> println("Crab")
    "S" -> println("Star")
    "W" -> println("Whale")
    else -> println("Human")
}
  • check the range 

  • The when expression doesn't need an initial value. 

7. Booleans

  • Nullable Booleans are either true, false or null
  • When working with them you can't do this
val isSponge:Boolean? = null

val str = if(isSponge) "sponge is true" else "sponge is false"
println(str)
  • You have to specifically check it's value
val isSponge:Boolean? = null

val str = if(isSponge == true) "sponge is true" else "sponge is false"
println(str)

'Self-study > Kotlin' 카테고리의 다른 글

[Kotlin] Basic2  (0) 2024.01.19