# Untitled

unknown
plain_text
a month ago
31 kB
7
Indexable
Never
```kotlin.addition

1. standardlibraries
1.1. BigDecimal.kt

import java.math.BigDecimal
import java.math.RoundingMode

/*
The size of numbers isn't really limited by anything but the physical memory of your computer.
In the case of BigDecimal, you can have as many digits after the point as you want.
*/

fun creatingObjectsOfDecimal() {
//  The first way is creating it from the String object
val firstBigDecimal = BigDecimal("10000000000000.5897654329")
val secondBigDecimal = BigDecimal(readln()) // Store the input number

// The second option is creating it from Double
var bigDecimal = BigDecimal(10000000000000.5897654329)

// You can convert numbers of other types to BigDecimal
val number = 100000.50000
bigDecimal = number.toBigDecimal()
}

fun arithmeticOperationsOfBigDecimal() {
// BigDecimal is an immutable class. If you try to modify an existing object, it is created again.

var first = BigDecimal("0.2")
var second = BigDecimal("0.1")

val addition = first + second   // 0.3
val subtraction = first - second   // 0.1
val multiplication = first * second // 0.02
val division = first / second   // 2.0
val remainder = first % second // 0.0

// decrement
val decrement = --first //  -0.8
// increment
val increment = ++first //  0.2
// unary minus, turning to opposite sign
val reverse = -first  //  -0.2
// absolute value
val module = first.abs()  //  0.2
// raise to the power, works only with Int
val power = first.pow(3)
}

fun roundingControl() {
val fractionalNumber= 1234.5678.toBigDecimal()
println(fractionalNumber.scale()) // 4
println(fractionalNumber.setScale(3, RoundingMode.FLOOR)) // 1234.567
println(fractionalNumber.setScale(3, RoundingMode.CEILING)) // 1234.568

var bigDecimal = BigDecimal("0.55")
println(bigDecimal.setScale(1, RoundingMode.HALF_DOWN)) // 0.5
println(bigDecimal.setScale(3, RoundingMode.UNNECESSARY)) // 0.550

bigDecimal = BigDecimal("999999999999999999.99999999999999")
bigDecimal = bigDecimal.setScale(3, RoundingMode.HALF_UP)
println(bigDecimal) // 1000000000000000000.000
}

fun roundingInArithmeticOperators() {
var dividend = BigDecimal("0.9865745")
var divisor = BigDecimal("3.543")
var quotient = dividend / divisor    // 0.2784574
quotient = dividend.setScale(4, RoundingMode.CEILING)/ divisor   // 0.2785

dividend = BigDecimal("10")
divisor = BigDecimal("3")
quotient = dividend / divisor    // 3
quotient = dividend.setScale(4, RoundingMode.CEILING)/ divisor   // 3.3333

val first = BigDecimal("7.7777")
val second = BigDecimal("3.3")

val addition = first + second   // 11.0777; The result scale is 4 (max of the scales)
val subtraction = first - second   // 4.4777; The result scale is 4 (max of the scales)
val multiplication = first * second // 25.66641; The result scale is 5 (sum of the scales)
}

fun main() {
roundingControl()
}

########################################

1.2. BigInteger.kt

import java.math.BigInteger

/*
The Java Class Library provides a class called BigInteger for processing very large numbers (both positive and negative).
The size of a stored number is limited only by the available amount of memory.

The BigInteger class is immutable which means functions and operators of the class return new instances instead of changing existing ones.
*/

fun main() {
//    arithmeticOperations()
functionsOfBigInteger()
}

fun creatingObjectOfBigInteger() {
val maxLong = Long.MAX_VALUE
println(maxLong) // 9223372036854775807

var number = BigInteger("62957291795228763406253098")
number = BigInteger.valueOf(9223372036854775807)

val zero = BigInteger.ZERO // 0
val one = BigInteger.ONE   // 1
val ten = BigInteger.TEN   // 10

val numToBigInt = 1234.toBigInteger()
val strToBigInt = "1234".toBigInteger()
}

fun arithmeticOperations() {
var number = BigInteger("62957291795228763406253098")
val ten = BigInteger.TEN   // 10

println(number + ten)
println(number * ten)
println(++number)
}

fun functionsOfBigInteger() {
val oneHundred = 100.toBigInteger()
val nine = 9.toBigInteger()
val (result, remainder) = oneHundred.divideAndRemainder(nine) // 11 and 1

var number = BigInteger("-8")
println(number.abs()) // 8

// The gcd function returns the greatest common divisor of two numbers.
val eight = BigInteger.valueOf(8)
val six = BigInteger.valueOf(6)
println(eight.gcd(six)) // 2

}

##########################################

1.3. MyRandom.kt

import kotlin.random.Random

fun main() {
// typesOfRandomNumbers()
// customRanges()
pseudorandomNumbersAndSeeding()
}

fun typesOfRandomNumbers() {
// generates an integer value between Int.MIN_VALUE and Int.MAX_VALUE (inclusive)
println( Random.nextInt() )
// generates a long value between Long.MIN_VALUE and Long.MAX_VALUE (inclusive).
println( Random.nextLong() )
// generates a float value between 0 (inclusive) and 1.0 (exclusive)
println( Random.nextFloat() )
// generates a double value between 0 (inclusive) and 1.0 (exclusive)
println( Random.nextDouble() )
// same thing one more time
println( Random.nextDouble() )
}

fun customRanges() {
// generates a non-negative integer value less than 100
println(Random.nextInt(100))
// generates an integer value between -1000 (inclusive) and 100 (exclusive)
println(Random.nextInt(-1000, 100))

// generates a non-negative long value less than 100
println(Random.nextLong(100))
// generates a long value between 1 (inclusive) and 100 (exclusive)
println(Random.nextLong(1, 100))

// generates a non-negative double value less than 5.0
println(Random.nextDouble(5.0))
// generates a double value between 0.0 (inclusive) and 5.0 (exclusive)
println(Random.nextDouble(0.0, 5.0))

// Notice that nextFloat is the only function that doesn't allow specifying the custom range
// Random.nextFloat(5.0)
}

fun pseudorandomNumbersAndSeeding() {
// Every time the function is called, it gives us the next number in a predefined sequence.
// These numbers are called pseudorandom, and they are not completely unpredictable!
val randomGenerator42 = Random(42) // the generator takes the seed
for (i in 0..5) {
println(randomGenerator42.nextInt(100))
// In Kotlin 1.4, this code will always generate the same six numbers — 33, 40, 41, 2, 41, 32 — even on different machines.
}

// the default generator will give us a new sequence every time.
// the same generator we use when we call Random.nextInt(), Random.nextFloat() etc.
val defaultGenerator = Random.Default
for (i in 0..5) {
defaultGenerator.nextInt(100)
}
}

###################################

2. Addition.kt

###################################

kotlin.basics

1. inputandoutput
1.1. Readln.kt

fun main() {

// useReadln()
// readMultipleValues()

print("\${readln()} \${readln()} \${readln()} \${readln()} \${readln()}")
}

fun useReadln() {

val line = readln() // line co kieu la String
println(line)

println("Enter any number: ")
val number = readln().toInt()
println("You entered the number: ")
println(number)

val a = readln()
val b = readln().toInt()
val c = readln()
print(a)
print(" ")
print(b)
print(" ")
print(c)
}

fun readMultipleValues() {

val (a, b) = readln().split(" ")
println(a)
println(b)
}

#####################################

1.2. StandardInput.kt

import java.util.*

/*
Mac dinh standard input lay du lieu tu ban phim, no cung co the lay tu file
*/

fun main() {

val scanner = Scanner(System.`in`)
val name = scanner.next()
println("Hello \$name")
println(name.toBoolean())

scanner.close() // tranh tieu thu tai nguyen PC
}

fun printName() {
val scanner = Scanner(System.`in`)
print("Enter your name: ")
val name = scanner.nextLine()
val greeting = "Hello \$name"
println(greeting)
}

######################################

2. stringformatting
2.1. StringFormatting.kt

fun main() {
// basicSyntax()
// specialFormatSpecifiers()
// widthAndJustification()
// formattingInteger()
formattingFloatingPointNumbers()
}

fun basicSyntax() {
var string = String.format("%s %s", "Hello", "World")
println(string)

string = "%s %S".format("Hello", "Thieu")
println(string)

val str1 = "Kotlin"
val str2 = "the best language"

// %s is used to represent the String value,
// %1 is used to represent first argument
// %2 is used to represent second argument
var str = String.format("%1\\$s is %2\\$s", str1, str2)
println(str)

str = String.format("%2\\$s is %1\\$s", str1, str2)
println(str)

str = String.format("%s - %1\\$s is %s", str1, str2)
println(str)  // Kotlin - Kotlin is the best language
}

fun specialFormatSpecifiers() {
println(String.format("The percentage of%nthis amount is 30%%.\nIt is easy to remember."))
//    The percentage of
//    this amount is 30%.
//    It is easy to remember.
}

fun widthAndJustification() {
// The %s specifier can be modified in order to define the space an argument can occupy and its alignment.
println("%10s".format("String"))
println("%-1s".format("String"))
println()

// If N is a positive integer, then %Ns denotes that the argument should occupy the space of N characters (width indicator).
// In case N is smaller than the string length, the string will occupy the space equal to its length (it is not truncated).
// By default, a string is right-aligned within its available space.
val str = "String"
for (i in 1..15) {
println("%\${i}s".format(str))
}

// For left justification, %-Ns should be used.
val s1 = String.format("%8s %8s", "Hello", "World")
println(s1)

val s2 = String.format("%-6s %-8s", "Hello", "World")
println(s2)
}

fun formattingInteger() {
// %0Nd: Leading zeros fill in the indicated width.
// %,d: Thousands divisor.
// %+d: Number always signed, even if positive.
// % d: For a positive number, insert one leading space.
// %(d: Put a negative number in parentheses, without the minus sign.

val int1 = 1234
val int2 = -4567

println(String.format("%d", int1))       //1234
println(String.format("%8d", int1))      //    1234
println(String.format("%-8d", int1))     //1234
println(String.format("%+d", int1))      //+1234

println(String.format("%+d", int2))      //-4567
println(String.format("%09d", int1))     //000001234
println(String.format("%,10d", int1))    //     1,234
println(String.format("%+,010d", int1))  //+00001,234

println(String.format("%-+,10d", int1))  //+1,234
println(String.format("% d", int1))      // 1234
println(String.format("% d", int2))      //-4567
println(String.format("%(d", int2))      //(4567)
}

fun formattingOctalAndHexadecimalNumbers() {
// %o: octal
// %x: hexadecimal
// Note that the normal integer "+" , ",", (space), and "(" formatting properties are incompatible with these format specifiers.
// The # formatting indicator can be used in order to lead an octal number with 0 or a hexadecimal number with 0x.

val int1 = 3465
val int2 = -7896

println(String.format("%o", int1))     //6611
println(String.format("%o", int2))     //37777760450
println(String.format("%#o", int1))    //06611

println(String.format("%8o", int1))    //    6611
println(String.format("%-8o", int1))   //6611
println(String.format("%09o", int1))   //000006611

println(String.format("%x", int1))     //d89
println(String.format("%X", int2))     //FFFFE128
println(String.format("%#X", int1))    //0XD89

println(String.format("%8x", int1))    //     d89
println(String.format("%-8X", int1))   //D89
println(String.format("%09X", int1))   //000000D89
}

fun formattingFloatingPointNumbers() {
// For normal decimal representation, we use %f.
// It has all the formatting properties of %d, with the addition of an indicator to control the number of the decimal places.

// If N and P are positive integers, then %N.Pf or %.Pf denote that the number should have P decimal digits.
// Note that the number is also rounded up.
// If P is larger than the number of actual decimal digits, then trailing zeros are added so their number is exactly P.

var double1 = 1234.5678
var double2 = -1234.5678

println(String.format("%-15.2f %f", double1, double2)) //1234.57         -1234.567800
println(String.format("%+,-10f", double1)) //+1,234.567800

println(String.format("%f", double1))      //1234.567800
println(String.format("%f", double2))      //-1234.567800
println(String.format("% f", double1))     // 1234.567800
println(String.format("% f", double2))     //-1234.567800

println(String.format("%(f", double1))     //1234.567800
println(String.format("%(f", double2))     //(1234.567800)
println(String.format("%+f", double1))     //+1234.567800
println(String.format("%,f", double1))     //1,234.567800

println(String.format("%-15f", double1))   //1234.567800
println(String.format("%015f", double1))   //00001234.567800
println(String.format("%15.2f", double1))  //        1234.57
println(String.format("%.3f", double1))    //1234.568
println(String.format("%.6f", double1))    //1234.567800

// In order to get a string represented in scientific notation, the %e (lower case "e") or %E (upper case "E")
// format specifiers should be used. These specifiers are incompatible with the "," property.

println(String.format("%e", double1))      //1.234568e+03
println(String.format("%E", double2))      //-1.234568E+03
println(String.format("%15.2e", double1))  //       1.23e+03
println(String.format("%.9E", double1))    //1.234567800E+03

// we can use the %g or %G format specifier, which may choose the decimal or the scientific notation

double1 = 1000.0
double2 = 1000000.0

println(String.format("%g", double1))  //1000.00
println(String.format("%g", double2))  //1.00000e+06
println(String.format("%G", double2))  //1.00000E+06
}

fun booleanAndCharacter() {
val boolean = true
println(String.format("%b",boolean))    //true
println(String.format("%B",boolean))    //TRUE

val char = 'a'
println(String.format("%c", char))     //a
println(String.format("%C", char))     //A

// Note:
// %n - Newline
// %% - the % character
}

###############################

3. KotlinClass

class KotlinClass {

fun printHello() {
println("Hello world")
}
}

##################################

4. KotlinFile.kt

fun main() {
println("Hello world!!!")
}

fun letMethod() {
val b:Int? = null
var a = b?.let {
if (it > 0) return@let 1 else -1 // co the dung return@let hoac khong
}

val c = 1
val d = c.let {
if (it > 0) 1 else -1
}
println(a)
}

##################################

kotlin.controlflow

1. controlstructure
1.1. ifexpression
1.1.1. IfExpression.kt

/*
Trong Kotlin, if la mot bieu thuc (expression) chu khong phai mot cau lenh (statement)
*/

fun main() {
ifExpression()
}

fun ifExpression() {
val a = readln().toInt()
val b = readln().toInt()
val max = if (a > b) a else b

if (a < 0) {
println(1)
} else if (b < 0) {
println(2)
} else {
println(3)
}
}

fun whenExpression() {
// su dung when thay cho if-else-if
val number = 3
when (number) {
1 -> println("One")
2 -> println("Two")
3 -> println("Three")
4 -> println("Four")
else -> println("Number is greater than four")
}

val message = when (number) {
1 -> "One"
2 -> "Two"
3 -> "Three"
4 -> "Four"
else -> "Number is greater than four"
}

when {
number < 0 -> println("Negative number")
number in 1..10 -> println("Number between 1 and 10")
number % 2 == 0 -> println("Even number")
else -> println("Odd number greater than 10")
}
}

###################################

1.2. loop
1.2.1. forloop
1.2.1.1. Exercise.kt

fun main() {
rightRotation()
}

fun rightRotation() {
val n = readln().toInt()  // 5

val numbers = mutableListOf<Int>()
repeat(n) {
numbers.add(readln().toInt())  // 1 2 3 4 5
}

val position = readln().toInt() % n  // 1

for (i in 0..(n - 1 - position)) {
numbers.add(numbers[i])
}

for (i in (n - position) until numbers.size) {
print("\${numbers[i]} ")  // 5 1 2 3 4
}
}

#####################################

1.2.1.2. Main.kt

fun main() {
// Iterating through a range
for (i in 1..4) {
print("\$i ")
}
println()

for (ch in 'a'..'c') {
print("\$ch ")
}
println()

// Iterating through a String
val str = "Hello!"
for (ch in str) {
print("\$ch ")
}

// Iterating in the backward order
for (i in 4 downTo 1) {
print("\$i ")
}
println()

// Excluding the upper limit
for (i in 1 until 4) {
print("\$i ")
}
println()

// Specifying a step
for (i in 7 downTo 1 step 2) {
print("\$i ")
}
println()

}

###################################

1.2.2. repeat
1.2.2.1. Main.kt

fun main() {
repeat(3) {
println("Hello")
}

// Neu so lan lap la 0 hoac so am thi Kotlin se bo qua vong lap do
repeat(-1) {
println("Zero or Negative")
}

// Iterator
repeat(5) {
print("\$it ")
}
println()

// Reading and processing data in a loop
val n = readln().toInt()
var sum = 0

repeat(n) {
val next = readln().toInt()
sum += next
}

println(sum)
}

##################################

1.2.3. whileloop
1.2.3.1. Main.kt

fun main() {

// While loop
var i = 0
while (i < 5) {
print("\$i ")
i++
}
println("...")

var letter = 'A'
while (letter <= 'Z') {
print(letter)
letter++
}
println()

// Do...while loop
do {
val n = readln().toInt()
println(n)
} while (n > 0)
}

fun exercise1() {
val n = readln().toInt()
var num = 1
var count = 0
while (count < n) {
if (count + num <= n) {
repeat(num) {
print("\$num ")
}
count += num
} else {
repeat(n - count) {
print("\$num ")
}
count = n
}

num++
}
}

#######################################

1.3. whenexpression
1.3.1. WhenExpression.kt

fun main() {
exercise2()
val x = 11
when (x) {
10, 11 -> print("a")
11, 12 -> print("b")
}

}

fun alternatives() {
val (var1, op, var2) = readln().split(" ")

val a = var1.toInt()
val b = var2.toInt()

when (op) {
"+" -> println(a + b)
"-" -> println(a - b)
"*" -> println(a * b)
else -> println("Unknown operator")
}

when (op) {
"+", "plus" -> println(a + b)
"-", "minus", -> println(a - b) // trailing comma
"*", "times" -> println(a * b)
else -> println("Unknown operator")
}

when (op) {
"+", "plus" -> {
val sum = a + b
println(sum)
}
"-", "minus" -> {
val diff = a - b
println(diff)
}
"*", "times" -> {
val product = a * b
println(product)
}
else -> println("Unknown operator")
}
}

fun expression() {
val (var1, op, var2) = readln().split(" ")

val a = var1.toInt()
val b = var2.toInt()

val result = when (op) {
"+" -> a + b
"-" -> a - b
"*" -> a * b
else -> "Unknown operator"
}
println(result)

}

fun conditionsAndRanges() {
val (var1, var2, var3) = readln().split(" ")

val a = var1.toInt()
val b = var2.toInt()
val c = var3.toInt()

println(when (c) {
a + b -> "\$c equals \$a plus \$b"
a - b -> "\$c equals \$a minus \$b"
a * b -> "\$c equals \$a times \$b"
else -> "We do not know how to calculate \$c"
})

val n = readln().toInt()
when (n) {
0 -> println("n is zero")
in 1..10 -> println("n is between 1 and 10 (inclusive)")
in 25..30 -> println("n is between 25 and 30 (inclusive)")
else -> println("n is outside a range")
}
}

fun whenWithoutArguments() {
val n = readln().toInt()

when {
n == 0 -> println("n is zero")
n in 100..200 -> println("n is between 100 and 200")
n > 300 -> println("n is greater than 300")
n < 0 -> println("n is negative")
// else-branch is optional here
}
}

fun exercise1() {
val (var1, op, var2) = readln().split(" ")

val a = var1.toLong()
val b = var2.toLong()

when (op) {
"+" -> println(a + b)
"-" -> println(a - b)
"*" -> println(a * b)
"/" -> {
if (b == 0L) {
println("Division by 0!")
} else {
println (a / b)
}
}
else -> println("Unknown operator")
}
}

fun exercise2() {
val room = readln()

when (room) {
"rectangle" -> {
val a = readln().toDouble()
val b = readln().toDouble()
println(a * b)
}
"triangle" -> {
val a = readln().toDouble()
val b = readln().toDouble()
val c = readln().toDouble()

val p = (a + b + c) / 2
println(Math.sqrt(p * (p - a) * (p - b) * (p - c)))
}
"circle" -> {
val r = readln().toDouble()
println(r * r * 3.14)
}
}
}

#########################################

2. exception
2.1. exceptiontype
2.1.1. AvoidingNPE.kt

fun main() {
var name: String? = "Kotlin"

// Safe Calls (?.): allow you to access properties and methods of nullable objects without risk of a NullPointerException
var length = name?.length // length is null if name is null

// Elvis Operator (?:): lets you provide an alternative value in case the expression to its left is null.
length = name?.length ?: 0 // length is 0 if name is null

// Non-Null Assertion (!!): Transforms a nullable type to a non-nullable type, throwing an exception if the value is null.
length = name!!.length // Throws NullPointerException if name is null

// Safe Casting (as?)
val x: Any = "Kotlin"
val y: String? = x as? String // y is safely cast to String or null

// Let function
// Use let for Null Checks: The let function can be used to execute block of code only if the variable is not null.
name?.let {
println("Name is \$it")
}

// Apply function
// Use apply for Configuration: Use apply on a nullable object to configure it if it's not null.
name?.apply {

}

// takeIf and takeUnless function
// These functions are useful for conditional checks that return null if the condition is not met.
val input = "ABC"
val positiveNumber = input.takeIf { it.length > 0 }
val notBlankString = input.takeUnless { it.isBlank() }
println(positiveNumber)
println(notBlankString)

// Design APIs for Null Safety: When designing APIs, use default parameters and provide non-null types.
fun process(input: String = "") { /*...*/ }
}

#####################################

2.1.2. Exception.kt

/*
Throwable:
1. Error
2. Exception
2.1. RuntimeException
2.1.1. ArithmeticException
2.1.2. NumberFormatException
2.1.3. IndexOutOfBoundsException -> StringIndexOutOfBoundsException
*/

fun main() {
makeAnException()
}

fun hierarchyOfException() {
// throws ArithmeticException
val example = 2 / 0

// throws NumberFormatException
val string = "It's not a number"
val number = string.toInt()

// throws StringIndexOutOfBoundsException
val sequence = "string"
println(sequence[10])
}

// Khi throw an exception thi kieu tra ve la Nothing
fun makeAnException(): Nothing {
throw Exception("I'm an exception!")
}

fun calculateSpentMoney(total: Int, itemPrice: Int): Int {
if (total < 0) {
throw Exception("Total can't be negative")
}
if (itemPrice < 0) {
throw Exception("Item price can't be negative")
}
if (itemPrice == 0) {
return 0
}
val amountToBuy = total / itemPrice
return amountToBuy * itemPrice
}

#######################################

2.1.3. Nothing.kt

fun main() {
// nothing()
}

fun nothing() {
// In Kotlin, Nothing is a unique type because it doesn't have an instance.
// It can be used when a function never returns a value, not even Unit.
// In essence, Nothing is a subtype of every known type in Kotlin.
// It means that it can represent a value of any type in terms of type checks.

fun fail(): Nothing {
throw RuntimeException("This function always throws an exception")
}

fun calculatePercentage(marks: Int, total: Int): Float {
if (total == 0) {
fail()  // 'fail()' is used where a Float is expected
}
return (marks/total.toFloat()) * 100
}

// If total is zero, it's impossible to calculate the percentage, but the function demands a Float return type.
// You can't return a null (assuming the function doesn't accept a nullable Float) or any other value.
// One effective way to handle this is by using a function that returns Nothing.
}

fun todoFunction() {
// The TODO function in Kotlin is a standard library function designed to give developers a consistent way to
// mark code that hasn't been implemented yet
// Notably, its signature fun TODO(reason: String): Nothing
// reveals that it returns the Nothing type and accepts a reason parameter explaining why the function isn't implemented yet.
// In essence, TODO throws a NotImplementedError with the given reason.

TODO()
TODO("Feature not implemented yet")
println("This statement is unreachable") // This will never execute due to TODO()

// What makes TODO unique is that you can use it wherever a value is expected, regardless of the type.
val x = if (1 > 0) {
TODO("Not decided what to do yet")
} else {
// some other case
}
}

####################################

2.2. handling
2.2.1. TryCatch.kt

import java.lang.NumberFormatException

// Khong giong như Java hay nhieu ngon ngu khac, try co the la mot bieu thuc trong Kotlin

fun main() {
intDivision()
}

fun example() {
println("Before the try-catch block") // it will be printed
try {
println("Inside the try block before an exception") // it will be printed
println(2 / 0) // it throws ArithmeticException
println("Inside the try block after the exception") // it won't be printed
} catch (e: ArithmeticException) {
println(e.localizedMessage) // it will be printed
}

println("After the try-catch block") // it will be printed
}

fun intDivision() {
val x = readln()
val y = readln()

println(
try {
x.toInt() / y.toInt()
} catch (e: ArithmeticException) {
println("Exception: division by zero!")
0
} catch (e: NumberFormatException) {
println("Read values are not integers.")
0
}
)
}

######################################

2.2.2. TryCatchFinally.kt

fun main() {

}

fun threeMagicWords() {
try {
println("Inside the try block")
println(2 / 0) // throws ArithmeticException
} catch (e: Exception) {
println("Inside the catch block")
} finally {
println("Inside the finally block")
}

println("After the try-catch-finally block")
}

fun omittingBlocks() {
try {
val a = 0 / 0 // throws ArithmeticException
} finally {
println("End of the try block") // will be executed
}
println("End of the program") // will not be printed
}

fun expression() {
val number: Int = try {
"2a".toInt()
} catch (e: NumberFormatException) {
0
} finally {
println("Inside the finally block")
}

println(number)
}

####################################

3. function
3.1. DefaultArguments.kt

fun main() {
printTest("Te", "st")
printLine()
printLine("1")
printLine(end = "2")
printLine(end = "3", line = "test")

println(sum5(8, 11))

repeat("String")
repeat("String", 5)
}

fun printTest(line: String, end: String) = println("\$line\$end")

fun printLine(line: String = "", end: String = "\n") = println("\$line\$end")

fun sum5(a1: Int = 0, a2: Int = 0, a3: Int = 0, a4: Int = 0, a5: Int = 0): Int {
return a1 + a2 + a3 + a4 + a5
}

fun repeat(s: String, times: Int = 1, upperCase: Boolean = false): String = "\$s - \$times -\$upperCase"

###################################

3.2. Function.kt

fun main() {
println(perimeter(0.0, 0.0, 12.0, 0.0, 0.0, 5.0))

val arr = arrayOf("a", "b", "c")
foo(*arr)
foo(strings = arrayOf("x", "y", "z"))
}

fun perimeter(
x1: Double = 0.0, y1: Double = 0.0,
x2: Double = 0.0, y2: Double = 0.0,
x3: Double = 0.0, y3: Double = 0.0,
x4: Double = x1, y4: Double = y1
): Double {
val a = Math.hypot(x1 - x2, y1 - y2)
val b = Math.hypot(x2 - x3, y2 - y3)
val c = Math.hypot(x3 - x4, y3 - y4)
val d = Math.hypot(x4 - x1, y4 - y1)
return a + b + c + d
}

fun max(
a: Int,
b: Int,
): Int { // you can swap arguments without worrying about commas
return if (a > b) a else b
}

fun printSum(a: Int, b: Int): Unit {
println(a + b)
// Neu ham khong tra ve gia tri gi thi co the de Unit hoac khong gi ca
}

// Single-expression functions
fun sum(a: Int, b: Int): Int = a + b

fun isPositive(number: Int) = number > 0 // Co the de kieu tra ve hoac khong

fun divideTwoNumbers(a: Long, b: Long) = if (b != 0L) a / b else println("Division by 0!")

// vararg: variable number of arguments
fun foo(vararg strings: String) {
for (string in strings) {
println(string)
}
}

#####################################

3.3. InlineFunction.kt

```
Leave a Comment