Kotlin Geek Series 🤓
Let’s get down to the nitty-gritty of Kotlin
Episode 1 - Basic Types
We are heading to an exploration journey toward those nitty-gritty Kotlin details that may win you a T-shirt on a programming conference’s victorine or grant you a highly paid job, who knows! (A word of advice: take the T-shirt, money won’t make you happy but an ugly programmer’s tee — for sure!).
What you will learn? Facts about:
- Floating-point types
- Explicit conversions
- Arithmetic operations
- Unsigned integers
- Strings
- Arrays
If you are impatient just check my code at the end of the article. It could be used instead of the article itself.
This article will be organized as a question-answer quiz, cause I know you are smart and won’t bore you with information you already know. Each correct answer gives you one Kotlincoin (yay, you will be a millionaire!)
Floating-point types
- What is the type of this expression?
val pi = 3.14
▶ It is Double
. All float point literals are double by default.
- What is the difference between
Double
andFloat
?
▶ Double
has 15–16 digits, while Float
has 6–7.
- What is the actual value of this expression?
val fl = 2.12345678f
▶ It is 2.1234567. If a Float
value contains more than 6–7 decimal digits, it will be rounded. In my case it was not rounded but trimmed.
- Can you call a function with
Double
parameter with aInt
orFloat
value?
▶ No! No implicit widening. You can use only Double
.
- Can you write a number as
val oneMillion = 1_000_000
▶ Yes!
- How Kotlin cast Numbers to Java?
▶ Numbers are casted to Java primitives if possible. If type is Int?
it is boxed in Java’s Integer
.
- Can you compare accurately floating point values like that
3.145 == 3.14
or 3.12 < 42
?
▶ Yes! There are equals
and compareTo
implementations for Float
and Double
so your comparision is safe and accurate.
- How you can check if number is in certain range?
▶ x in a..b
- How you can check if number is not in certain range?
▶ x !in a..b
Explicit conversions
- Could you cast Byte to Int?
val byte: Byte = 1
val int: Int = byte
▶ No, you need to use byte.toInt()
- What about this expression?
val byte: Byte = 1
val result: Int = 1 + byte
▶ Yes, in an arithmetic operation the cast happen automatically.
Smaller types are NOT implicitly converted to bigger types.
Arithmetic operations
- What is the result?
val x = 5 / 2
▶ It is 2. Two integers return integer, fraction (0.5) is removed.
- How can you return Double?
▶ val x = 5 / 2.toDouble()
Explicitly convert one of the arguments to a floating-point type.
Unsigned integers
- Do we have unsigned integers in Kotlin? Example?
▶ Yes! UByte
ranges from 0–255 an unsigned bit integer
val b: UByte = 1u
- Using our pervious knowledge can we do
val i: Int = 1u
?
▶ No, you can’t cast Byte to Int explicitly, and you can’t cast an unsigned to signed value either, so it is double NO (No, No)
Booleans
- Can you have nullable
Boolean
?
▶ Yes. There is Boolean?
Characters
- How do you represent a literal?
▶ Single quote '1'
val char: Char = ‘a’
- Can you take the number value represented by Char and use it in expression? See the example:
val numChar: Char = '9'
val sum = numChar + 1
▶ Yes. Use digitToInt()
Kotlin goody.
val sum = numChar.digitToInt() + 1 // sum will be 10
Strings
- Can you iterate over characters of
String
?
▶ Yes. Just use a for loop.
val string = "12345567"
for(ch in string){
print("$ch, ")
}
- Will this create a new String object?
println(str.uppercase()) // Create and print a new String object
▶ Yes. All operations that transform strings return their results in a new String
object because String is immutable class.
- How do you concatenate String?
▶ Use +
BUT in most cases using string templates or raw strings is preferable to string concatenation.
- Can you concatenate like this:
val s = 1 + "abc"
▶ No, the first element in the expression needs to be String.
String literals
- How do you escape character?
▶ Use backslash “\”
.
- How do you escape a whole string?
▶ Use triple quote “””
.
println("""Sentence 1
Sentence 2 on new line
""")
- How you can remove the empty space around a string?
“ A user entered sentence… “
▶ Use trimIndent()
.
val withoutIndent =
"""
ABC
123
456
""".trimIndent()
- How you can format text on few lines?
▶ Call trimMargin()
and use |
as margin prefix or set your own character.
String templates
- How you can embed code in a String for example
“Hello [value]”
?
▶“Hello $name”
may print Hello James.
- What about more complex stuffs
“Your age is [some date calculations]”
?
▶ Use curly braces if you need expression. “Your age is ${Period.between(bday, now)}”
.
- How you can insert the
$
character in a raw string?
▶ Use “${‘$’}”
.
println("Hello $name. You are ${Period.between(bday, LocalDate.now()).years} years old. You owe me 1${'$'} for this calculation!")
Arrays
- How do you create an array?
val array = arrayOf(3, 4, 5)
- How do you create an array initialized with null?
val arrayNul = arrayOfNulls<Int>(5)
- How do you get or set a value in array?
▶You can use get()
and set()
methods or overloaded operator []
arrayNul[2] = arrayNul[0]?.plus(arrayNul[1] ?: 1)
- Create array with string numbers from 0 to 4
val asc = Array(5) { i -> i.toString() }
- Is
Array<String>
assignable toArray<Any>
▶ No, but Array<out Any> is!
val stringArray = arrayOfNulls<String>(3)
// val anyArray: Array<Any> = stringArray -> won't compileval anyArray: Array<out Any?> = stringArray
Primitive type arrays
Arrays of primitive types without boxing overhead: ByteArray
, ShortArray
, IntArray
val intArray = intArrayOf(1, 2, 3)
These classes have no inheritance relation to the Array
class.
val intArray = intArrayOf(1, 2, 3)
val intArray2 = IntArray(3) // Will be initialized with 0
val intArray42 = IntArray(3) {42 } // Will be initialized with 42
val intArray4 = IntArray(3) { it * 1 } // Int array 1,2,3Code here:
Game time
Check out this code and play with it. Yay!
Oh..I just figured out that probably the best job is the one that supplies you with ugly T-shirts regularly. What do you think?