Thinc. First Code Android (Part II: Kotlin Syntax 101)
Now that we have set up Android Studio (and your device), let’s know the very basics of how to code first.
If you want to try writing along with this tutorial, you can start writing the code in Android Studio. In MainActivity.kt
file, try anything inside the override fun onCreate
function.
In an easy term (technically not correct), this is where your program starts, like public static void main(String[] args)
in Java, or int main()
in C. Every time you want to run the program, run the app with the green Run button.
Alternatively, you can try this by the official Kotlin site. However, some external libraries for Android will not be available in this site. You can use print()
or println()
(print new line after) for printing out the word (string) of the variables.
Now that you are ready, let’s get started!
Precaution: No need to read the whole thing at once. The whole thing here is basically the same amount of content we have to study in almost 1 semester!
⚠️ This is *definitely* not a 7-minute read, unless you are skimming. 🍭
Primitive Data types
Byte : integer from -128 to 127
Short: integer from -32,768 to 32,767
Int : integer from -2,147,483,648 to 2,147,483,647
Long : integer from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
Double : decimal from -3.4*10^38 to +3.4*10^38
Float : decimal from -1.7*10^308 to +1.7*10^308
Boolean: true or false
Char : character, ex: 'b', 'n', 'k', '4', '8', '柴', 'あ', '_', '@', '_', '草'
String : character(s), ex: "bnk48", "doge", "柴犬", "¯\_(ツ)_/¯"
Operations: Same as in most languages.
Number operations
a+b plus
a-b minus
a*b multiply
a/b divide
a%b remainder
a**b exponentsBoolean expressions (returns as a boolean)
a>b greater than
a<b less than
a>=b greater or equal to
a<=b less than or equal to
a==b equal to
a!=b not equal to
Declaring and assigning variables
- Declaring & Initializing & Assigning
You can also declare without data type, but it is not recommended, unless you have explicitly declared and know exactly what that data type is.
val yetAnotherVarName = yetAnotherValue //OK
- Declaring null-able data types
If your value can be null, put ‘?’ in front of the data type.
💡 Examples!
String literals
You can use ${variable}
inside the String to use these variables to concatenate (connect) as a String. Below is why Kotlin is better than Java.
Logging
We can’t use print() in the terminal of Android Studio, but we have Log
function to display your log for debugging purpose. You can see the log message in Logcat in Android Studio.
Log.d(tag,message) //debug
Log.i(tag,message) //info
Log.e(tag,message) //error
Log.v(tag,message) //verbose
Log.w(tag,message) //warning
Log.wtf(tag,message) //no context needed (stack trace of your error)
For simple uses, all of them will log for you, so you don’t really need to care what you should be choosing. As long as you name your tags uniquely, you can easily search for those tags.
💡 Examples!
Log.i(“Test”,”Hello Doggie”) will log as
“something bla bla bla com.example.yourapp I/Test: Hello Doggie”
in white text color.Log.e(“ERROR?”,”ERROR!!!”) will log as
“something bla bla bla com.example.yourapp E/ERROR?: ERROR!!!”
in red text.
📔 If you see the word Log in red, you need to import the library called Log, by Alt+Enter
for Windows, or option+Enter
(?) for Mac.
📔 The message
field has to be String, so if you need to Log a number or boolean or anything else, put .toString()
in the end. For example: myAge.toString()
.
If-else statement
You can also form more than 1 if-else chain.
💡 Examples!
⚠️ In the if-statement and any other syntax you’ll see that uses curly braces {}, anything that is defined inside that braces does not exist outside the braces.
When (shorthand of if-else)
When you check the condition of the same expression, you can shorten your code with the when statement. There are so many syntax for when
expression, see here for even more details. This is the standard syntax of when
expression.
💡 Examples!
Arrays/Lists
You can also assign variables to contain a collection of data as well. There are many ways to initialize and assign the array, but here is the very common way to do so.
There are 2 types of lists, List
and ArrayList/MutableList
. List
is not mutable, a.k.a. its elements cannot be changed. MutableList
is, as its name, mutable.
The concept of val
and var
still holds.
To access the elements of the list by index, use this below.
⚠️ Index of the array ALWAYS starts at 0 and ends at list.size-1
.
You can also change the mutable list with this syntax.
📔 Notice that your arrayList
is assigned by val
, but you can still change the element inside. What you cannot do, is changing the whole list as shown in line 3.
In your list
however, you cannot change the element inside, but with var
, you can reassign the whole thing.
🍎 For your conveniences, use MutableList
. You can always convert from MutableList
to List
or vice-versa using .toList()
and .toMutableList()
.
There are many functions to deal with lists and mutable lists. You can get the element of your list by index, remove the element, get the index of an element in the list, etc. I really suggest you to read the library of Kotlin along for even more available functions in the library. This will be shown in the examples below here.
💡 Examples!
Extra: Multidimensional Arrays/Lists
Your arrays/lists can also contain another lists! Just put the array/list inside!
📔 Each sublists doesn’t need to have the same size!
LÖÖPS
If you have to do the same thing many times, you can use a concept of LÖÖP.
In Kotlin, we have 2 main concepts of looping. Firstly, we basically want to do everything inside a collection. This concept is called iterator.
Anything that can be broken down into smaller data types are all collections. For example, List<Int>
is a collection of Int
.
🙊 Surprisingly, String
is also a collection! String
is a collection of Char
!
💡 Examples!
In this way, you would encounter 1 problem. What if I want to do just some parts of the lists? What if I want to use the index of each elements of the list to do something with the data? Iterators cannot really do that.
Another way to use for-loop is ranges.
🍌 It is essentially the same as the iterator, as range is also a collectible. Here is how you assign the value of range
.
You can explicitly define the range that you want to iterate in the for-loop.
for(i in firstNumber..lastNumber step stepNumber){
//do something
}// Your "i" will *increase* from firstNumber to lastNumber
Note! "step" can be ignored
If you want to decrease instead, use downTo
.
for(i in firstNumber downTo lastNumber step stepNumber){
//do another thing
}
You can also use the keyword until
to start from certain value, up until exclude the last number.
for(i in firstNumber until lastNumber step stepNumber){
//do the thing without lastNumber
}
📔 The until
is actually really useful and easy to read in this case. You can be definitely sure that your loop will run x times.
for(i in 0 until x){
//do something here x times
}
Now, what if you want to stop the for-loop in the middle of the loop? You can also use the keyword break
to stop your loop.
Or, what if you want to skip some values, but don’t want to stop the for-loop? You can also use the keyword continue
to skip everything else after it.
💡 Examples!
📔 For more information of ranges and how it works, here is the Kotlin doc.
Functions
You can also write your own function that performs the logic, so that you can call that function to do the logic at any times.
⚠️ You need to write the function outside the override fun onCreate()
(but still inside the class MainActivity
), or fun main()
. Basically, both of them are also functions.
Fun fact! You can use the function inside another functions as well. You can even have your function use itself! This is basically called “Recursion”. Recursion is a way to do the work by recursion. 🍭
💡 Examples!
That’s quite exhausting, isn’t it? Don’t worry, not everyone knows everything in the first try. You can always read Kotlin docs. I do it (almost) all the time when I’m not sure of anything. Have fun coding!
The next part of Kotlin 102 (not the next publication) will be Classes and Object-Oriented Programming concepts.
The next publication will be about creating our very first app! Stay tuned!
🔗 Extra links:
- Kotlin References https://kotlinlang.org/docs/reference/