Kotlin Crash Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] welcome to my kotlin crash course first of all i really want to thank you brad for giving me that opportunity that is nothing i can take for granted and if some of you really like my way of teaching here in this course then you can check out the first link in this video's description there you'll find the link to my channel i do all kinds of android development using kotlin from beginner to advanced for example a running tracker app or a news app and yeah if you are interested in that just check it out you will like it and regarding android i also plan to make another course where we'll just apply the knowledge from this kotlin crash course here to make a very simple android app and i guess when that is out brad will just link to that under this video as well so why would you actually learn kotlin it's not that popular yet but it is one of the most trending languages out there at the moment so the number of users is rising so quickly so right now it is mainly used for android development just because um google gives it first class support for android and just pushes it really hard but it's also getting more and more popular just for big enterprise applications and it is in my opinion on a good way to replace java in future so if you're new to programming java is just a programming language that is super spread in the industry but it is also a very old language and there are just nowadays many more modern languages for example kotlin that just do a lot of stuff much easier than these old languages like java and one reason why cotton is becoming so popular is that it is fully interoperable with java so those two languages compile to the same byte code and that means deep down on a system level we cannot differentiate if a program was initially written in kotlin or java and that allows us for example that we can use all the java libraries out there in kotlin as well and that is a big benefit because as i said java is an old language and there are very many libraries out there and we can just reuse them in kotlin now which is a modern language so if you're new to programming and don't know what a library is that is just a pre-written piece of code somebody else wrote that you can easily include in your project so you don't need to write that code on your own then a second big advantage of using kotlin is that it really does not need a lot of lines of code so again the comparison to java just because that is my opinion the main competitor of kotlin or the main language we can compare to um often if we would write a program in java and let's say that would take 4000 lines of code then it wouldn't be unusual if we would write the exact same program in kotlin that it needs like 2 500 lines of code or even 2 000. so 40 to 50 percent less lines of code just by using kotlin is not unusual and there are actually many many more advantages of kotlin that are more of technical nature which we will discover in this course okay so what do we actually need to start with kotlin if we would make android apps we would install a program called android studio which we don't do here because we don't want to make android apps that would just require android background and we really just want to focus on learning kotlin here and that is why we will use a program called intellij that is an ide so an integrated development environment that's just a program that makes it very convenient for us to write our code and installing that is actually very easy we just want to open our favorite browser here and don't worry microsoft edge is not my favorite browser that is just a virtual machine here to show you that setup part we want to search for intellij download and then you will see this page from jetbrains.com we click on that first result here and you can see we have two options the ultimate version or the community version the ultimate version is paid so we don't want that we don't need that that is just really professional software community is completely fine for us that is free we can just click on download then it should start we need to click on save here it will take a couple seconds and then i'll see you okay once that download is finished we want to click on run to run the installer and then wait a little moment we need to accept something here okay and there we go so that is as i said a very simple setup here we just want to click on next you can choose a destination folder so where you want to install that program to i will just leave that as it is and click on next then we can choose if we want to create a desktop shortcut i will just do that here for the 64-bit launcher we can update the context menu we don't want that you could create associations for file endings so that you can just double click on those files and intellij will open these files i'll also leave these unchecked and the rest as well so we will just click on next here click on install and then the program will install and i will see you after that okay so once the setup is finished we can check the checkbox here to run intellij and click on finish you can see there it is we could import settings here if we would have a previous installation of intellij then we could just import our old settings we don't have that right now so we want to check do not import settings we click ok and then wait a little moment and now it comes to the decision if you want to become a real programmer or not real programmers choose the dark theme now of course choose whatever you like here i'll choose dark theme we click on next then you can see we could modify some pre-installed tools here which are all pretty advanced we don't want to touch any of these right now so we just click on next to featured plugins these are just also plugins that you can install to your intellij ide that assist you with programming we also want to don't want to touch these so we just click on start using intellij idea and then this window should open for you hopefully it does and here you can see we can now create a new project which we want to do here we want to just create a project in which i will show you the basics of kotlin so that you are ready to use it and you can see we have several options here but before we can actually create a project here we need to install one more thing and that is the so-called jdk that stands for java development kit and that is just a toolkit that we need to be able to run kotlin and java programs or to develop them actually and for that we want to go back to our browser i'll open a new tab here and we want to visit adopt open jdk.net so there are several versions of this jdk here one is by oracle so the actual creators of java but that shouldn't be used here because that is paid so if you not not really paid but if you want to publish something that you made with oracle jdk then you need to pay for their lights license basically and this open jdk is the free version of that so you can just freely use that for development i will use the openjdk version 11 here which is for long term support so i really recommend you to use the same and we want to download this here and then we click on save again wait until the download is finished here and once it is we want to click on run again and install this jdk let's open this window here we can click on next at the first screen we want to accept the license agreement click on next again we can change the location again i will leave it as it is here click on next and we can click on install and once the setup is finished we can simply click on finish and go back to our intellij program here and click on kotlin because we want to create a kotlin project here and we will just choose this first option here jvm that stands for java virtual machine and that is just um special to java and kotlin so what actually happens is it will simulate an environment in which our program runs so virtual machine and that will just allow us to run our program everywhere so on mac os linux windows everywhere then we simply click on next here we can give our project a name let's just call that kotlin minus crash minus course and you can see the project will be created at this location here and we can select a project sdk here and that is exactly this jdk we just installed so right now we don't have anything selected here we want to open that and click on add jdk and then it will open our file system now you need to go to the location you installed your jdk2 so in my case program files adopt open jdk and we want to select this folder so jdk minus version 11 blah blah blah then we can click on ok and you can see now we have java version 11 selected here and it should look the same for you then and we can simply click on finish and intellij will create our project for us and open it as well so let's actually wait a little moment maximize that and you can see we get a tip of the day if you don't want these you can simply check this mark don't show tips and close this window so what we now want to do is we want to go to project on the top left corner here this will open our project hierarchy and that is actually a lot of stuff that we don't need to consider here we only worry about this src folder that stands for source and we just put all of our source files our kotlin files in that in which we will put our actual code and in this src folder we actually now want to create our first kotlin file so we right click go to new and select kotlin file or class and you can see we have several options here to choose from we just want to create a plain kotlin file and most of the other options will get clearer what they actually mean during this course and we will call this file main because this file will contain our so called the main function in kotlin every program needs this main function and that is just the entry point for our program so somehow when we actually run our program here it needs to know where it should start in the code and that will always be the main function and we can create that main function here let's make a little lens of code here little space by simply writing fun so for function then the name of the function which must be main in this case followed by two parentheses that don't contain anything and after that curly brackets so this will be the function our program will jump to when we launch it and between those two curly brackets we will now put the code that we want to execute when this main function is called and the mainstream example here for almost every programming tutorial is the so called hello world program so just a program that displays the text hello world and we can very easily do that by writing print line so print ln here and then in quotation marks we just write the text we want to print so printing doesn't actually mean printing here in your printer instead it means to print something to the console we won't do any graphical stuff here instead we will just have a console in which we can output text basically so for example hello world and now if you have done that we can go to the top side here click on run and click on this play symbol which says run and then we want to select main kt so we want to run this main kotlin file here click on that and then intellij will build our project so building means it will just take all of our resources all of our source files put them together to an executable file and run it and if you now take a look at the bottom here you can see it says hello world and that is actually your very first cotton program so what else can we do here let's remove our print line statement here again and instead what we will do is we want to create a variable so that is just a placeholder for a value here and we can declare a variable while by typing var and then we need to give that variable a name let's just call it x for example followed by a colon and now we need to specify the type this variable should have so in kotlin we can have several types we can assign to those variables so it could either be an integer number it could be a decimal number it could be just a character or for example a boolean a boolean is just a variable that either is true or false so let's actually just start with integer numbers here to specify that this variable x is now an integer we need to type in after that and now we can write an equals sign here and assign a value to that variable so for example three and that equals has now a different meaning than in math so if you're a little bit familiar with math then there this would mean that x is the same as three but what we actually mean in programming with this equals is that we set the value of x to 3. so we say x is now 3 and now we could for example just write another println statement here in the next line print line and in here we could write the value of x is followed by a dollar sign and then x so that dollar sign will just insert the actual value of x so it won't just print x to the console as it is here instead it will take a look which value is saved in that x variable which is three and then insert it here at that place so if we now rerun our program which you can also do in the top right corner from now on click on this play symbol take a look in our console then you will see now it prints the value of x is three and if we would now want to assign a new value to our x variable then we could simply do that afterwards for example and just use x so this time we don't need that var again and we could just assign a new number to it for example 4 and then we could print a line again the value of x is now and again use that dollar sign in x rerun our project our program here take a look in the console and you can see first it prints the value of x is 3 and afterwards it prints the value of x is now 4 because we changed it and actually there is another type of variable we can declare here so for now we use that var keyword so everything in kotlin that is highlighted in this orange here is called a keyword and another keyword for this would be val that will also declare a variable in the exact same way but this time you can see we get an error here if we hold on to this you can see val cannot be reassigned and that is the special thing of a vel that means we once we declare that val so that number here we cannot change it afterwards so this here won't work anymore and we can also remove the second print line statement here but this will run exactly the same way as it did before because that is just another way of declaring a variable and you should really prefer making your variables a val instead of a var if you don't need to change it later it's just good programming style to make your variables not changeable if they don't need to be changeable and we also actually don't need to explicitly define that this is an integer so if we leave this away and the colon as well then you can see this works as well so we don't get any error here and the reason for that is that cotton is smart enough to recognize that we set the value of x equal to a whole number and then it automatically knows that we wanted to declare an integer number here so let's actually see which other types we have here other than integer for example we could attach a capital l here after the three which would make our x is talk called a long long is just a format that can save much bigger numbers than integer so integer is a 32-bit number so it can save up to 2 to the power of 32 numbers and a long is a 64-bit number so it can save 2 to the power of 64 different numbers then we could make that x variable here of course also a decimal number by attaching a dot 3 3 for example and that works that is now called a double if we write it in that format but we also have another type of decimal numbers which is called a float by attaching this f after that number a float and a double both represent decimal numbers a double is just more precise than float but it also takes more memory so if you don't need that precision for decimal numbers then you should always prefer float so let's actually create some more variables here so you can remember that better first of all we had our whole number which we just declared by setting it to any number then we had our big number which was a long so we would set that to 3l in this case and you could see we can just make that number very big here i'll just leave it at 3 here and also remove that print line statement because we don't have that variable x now so it will give us an error because it doesn't know it and then we also have a precise decimal which is 3.33 for example we have a normal decimal which we set to 3.33 f we have as i said boolean expressions so either true or false so for example well i love vegetables is equal to false or we could use well i love pizza and we set that equal to true and by the way maybe you noticed how i write these variables so all of these start with a lower letter followed by a capital letter for each starting word and that is called camel case and you should always adapt to that type of spelling for your variables that is just a naming convention in kotlin and in bigger projects that makes it very easy for you and your team to immediately see which is a variable which is something else and we also are able to create simple characters so well i am a letter for example and we need to make these in these single quotation marks for example set that to a so what else cool stuff can we do here with these variables i will actually remove those again because what i want to show you now are so called arithmetic operators and i'm sure you know these from school those are just used for addition um subtraction multiplication and division and of course we have access to them in kotlin as well so what we can do is we can create a val val x and set that to for example three times four with this asterisk and if we would now print that again to our console so print line the value of x is dollar sign x and run our program take a look in our console in the bottom here you can see now it prints the value of x is 12 because it calculated three times four and save the value in our variable x and of course we can also replace that with a plus with a minus with a divide by but here we actually need to take care because if we would run our program here it will print the value of x is zero even though 3 divided by 4 is not 0 instead it's 0.75 but since we use integer numbers here so whole numbers the result of that division can also only be an integer number and what cotton will do in this case is it will just throw away the decimal part so it will throw away the 0.75 and just keep the zero so if we would actually need an accurate decimal result here we would need to make these variables for example a float by attaching an f afterwards so if we would now rerun this and take a look on the console you will see now the result so the value of x is 0.75 so that is now correct and another arithmetic operator that is not obvious is called modulo so what we could do is we could write 10 modulo 3 so that is represented by this percentage here and what that would mean or what that would do is it will take the 10 divide it by three and save the remainder of that division in x so in that case it would actually save one in x and that is for example something you need if you want to check if a specific number is even or odd so then we would just use let's say we want to check if 10 is an even number then we would use 10 modulo 2 so that would check if 10 is actually divisible by 2 because if the remainder of that division is 0 we know 10 must be an even number and if it is odd so if it is 1 then it must be an odd number but let's actually now take a closer look at booleans so these true or false values and i want to create a boolean here called min adult which are set to true and i will create another boolean am i a programmer which are also set to true and now with these booleans we have the possibility of so-called logical and comparison operators so if we would write val am i an adult programmer which is only true if both of these booleans is true then we can set that equal to min adult and so a double and that is important here am i a programmer so this will just check if this is true and if this is true and only both are true it will assign true to this so what we will do is we will remove that here and instead just print the value of min adult programmer run our program again take a look in the console and you can see it now prints true because both of our values here are true and if there is an option to and check there is also an option to or check so if one of these options is actually true if this one or this one is true or if both are true and we can do this by writing two of these lines i don't know the how they are called but that is basically an or check so it will check if this is true or if this is true and if one of these is at least true it will also assign true to this boolean then these were logical operators now we also have comparison operators so as the name says we want to compare something for example if am i an adult has the same value as am i a programmer and only then we want to assign true to this variable and we can do that with a double equals here so that is important that is a different equals than this one this single equals means we want to assign the value of this here to this variable and this double equals means we want to check if this is equal to this so to make that a little bit clearer we can actually put that into parentheses they are optional here but maybe this helps you to understand how this actually is evaluated and if there is a way to check if two variables actually have the same value there is also a way to check if two variables do not have the same value in that case we wouldn't write equals equals instead we would write this exclamation mark equals so that means this variable is not equal to this variable so let's just run this program to demonstrate that to you and if you take a look in the console now you can see it prints false because it will take a look at am i an adult which is true and it will take a look at mia programmer which is also true but only if this variable is not equal to this variable it will assign true to this variable and because those two are actually the same and we check if they are not the same the result will be false here and one last operator we can use here is the single exclamation mark operator which will just negate a boolean so for example we could attach that to the start of these parentheses and that will just negate that whole expression so if that is true this will make it false and if that is oops if that is false then this operator will make it true actually so as you saw if we when we didn't have that this returned false and if we use that now and run our program it will negate that whole expression again and now it will print true again so let's actually take a look at strings next we actually already used those strings before without much thinking about it so i will remove all of that code here again and create a string which is actually nothing else than just a text so well string is equal to and then we use those quotation marks again which we used in our print line function and here we can just type anything so kotlin is the best language for example and then simply use print line and print the string instead so before we just used that string here and use it directly in the print line function this time we just save this text in this object here and then print that value of that object basically so exactly the same as we did it with these variables before and there are also a bunch of functions you can call on that string object by writing a dot for example we could convert that to uppercase and if we would now run that take a look in the console and then it will just print our string in all uppercase here and that's actually already the whole magic of strings let's get to a very important concept next which you will find in every programming language out there the so-called if conditions so very often in programming we just need to check if a specific condition is true if it is we want to execute this code if it's false we want to execute this code so for example if we have a variable x here and set that to one plus one and now we want to check if that is actually two so we write if followed by parentheses and now these parentheses we have to write the conditions so that must be a boolean here because we either want to check if something is true or false and we could for example check now if x is the same as two so x equals equals two and then in curly brackets afterwards we can put the code that should be executed if this condition is actually true so in that case we could write a print line statement x is 2. and if that is not the case we could for example attach an else if so we can specify another condition so this check is actually done if this fails so if x is not equal to 2 then we could check if x is equal to 3 for example and curly brackets again then we would print x is three and then we also have the option to just put an else block here so it this will just check if x is two if it is it will execute this code if it is false then it will jump into this else if block will check if that is true if that is false it will just jump into this else block so in all other cases it will do whatever we put into this block of code here so in here we could write print line x is not two or three so if we would now run this take a look in the console again then you can see it will print x is two of course because 1 plus 1 is obviously 2. if we would change this to 1 plus 2 and run our program it will print x is 3 because that was false but that was true and if we would set that now to one plus three correct me if i'm wrong but i guess that is four and four is not equal to two four is also not equal to three so what it must do is it will jump into this else block so if we would now run this again it will print x is not two or three and the cool thing about if conditions in kotlin is that we can use them as expression so what that means is we could create a variable y here and we could set that equal to an if condition so for example if x is equal to 2 then we want to assign the value 2 to y and else we want to assign the value 3 to y so that is also a way how we can use if conditions here and next it comes to a very kotlin specific feature if you know java then you will know null values and null pointer exceptions so a null value is basically just a value that we can assign to a variable that will make the variable contain nothing so it's basically just an empty value for that variable and that was a big disadvantage of java because in java it could happen that our program crashed if we access such a variable that contains nothing and in cotton we're still able to do that because sometimes we just need to set a variable to null and kotlin will make sure that when we press run nothing could potentially crash our program and that is called null safety so kotlin is a null safe language and java is not so let's actually remove our if statements here again and declare an integer variable that we will just set to this null value i talked about so val x again and this time we explicitly need to declare the type with this colon again because a type is not nullable by default so we either have nullable types or non-nullable types and if a type is nullable then we have the option to assign this null value to it so to make it contain nothing and we can do that by first specifying the type this variable should have in our case just int and then appending a question mark after that and that will now allow us to set that variable to null and that is an example that might not tell you very well what this can be used for so let's create another val here and we want to accept the user input now so user input so for now we only printed something to the console but now we actually want to take input from the user and do something with that and we can set that equal to readline and you can see that is the type this function will return so the type that our user input variable will have and that is a nullable string so a text that is nullable and let's actually make a little calculator that can only add numbers by calling this number one and then we can copy this line paste it below call this number two so we now accept two user inputs two numbers and then we want to save the result of the addition of these numbers in this result variable so we set result equal to number one plus number two and right now this won't work because both our number one and number two are of type string and kotlin won't do a real addition here because it will treat those variables as strings and not as integer numbers that we really want to add here and because of that we need to convert these strings here to an integer we can do that with the dot to int function here and also the number two should be converted to an integer here and we get two errors here because this readline function could potentially return this null value if something goes wrong with that function and in that case we just need to make sure that at this part here these values can't be null because kotlin doesn't know how to add null values it only knows how to add numbers and to make sure that something is not equal to null we can use this question mark here before the dot so that will only execute this two-in function if this number one is not equal to null but in this case here this won't work because if this would be null it would still replace this expression with a null and then it still wouldn't know how to add this to another number so what we could do instead is use that double exclamation mark operator which will just assume that this number one is not equal to null so we basically tell kotlin trust me we know this is not null and if it would be null then our program would still crash so that is very similar to java we would do that here as well and if we now oops print that result here print line result and run our program take a look on the console we can now enter two numbers for example four enter five and you can see it will print the result of those two numbers so nine but i don't recommend using these double exclamation marks here because they could potentially make your program crash which you want to prevent of course instead we will use one more operator here after this readline function which is question mark colon and now we can specify another string that should instead be assigned to number one if this readline function returns null so in that case just a zero as a string and another zero here and that will just return or assign the result so the user input to this number one but if something goes wrong with that function and it returns null it will assign a zero instead the next concept i want to show you are actually so called lists so those are data containers we can use to save a bunch of variables in so we could for example create a shopping list here and set that equal to list off and in these angle brackets we now need to specify the type of the variables we want to save in that list for example a string because a shopping list usually contains texts and in these parentheses we can now list all of our items we want to have in this list so for example a lamborghini a pen house and a rolex just a normal purchase as a programming youtuber and now if we want to access the items in that list we could for example print one of these in a print line statement and use our shopping list followed by square brackets and you can see that now takes an index which is basically a number that refers to the item we want to print out so lists actually start with the index 0. so the first item has the index zero then the second item the index one index two and so on so if we would have more entries then it just would just go on like this for example if we want to print the first item we use shopping list at the index of 0. if we now run this take a look in the console you will see it will print lamborghini and here you need to be careful so if you would replace that 0 with a 3 that would mean we access a shopping list at the index of 3 which doesn't exist in our list because the the highest index is rolex with the index of 2 so that would make our program crash so you will always need to make sure that you don't access an index of a list that doesn't exist now there are two major types of lists we can have here in kotlin immutable lists and mutable lists so right now that is an immutable list we cannot add items to that list or remove items from that list or also we cannot change items so the value of items after we created that list but we could replace this list off with mutable list of and that would allow us to do this and by the way we also don't need this string specification here because we we just put strings into this list so kotlin will just recognize that we will have string values in that list so now we declared that as a mutable list which means we can always add and remove entries of that list so as you can see the highest index is rolex with the index two but what we could do now is we could use our shopping list dot add to add an item to that list which will just be appended to the last item of that list so after rolex and we could just specify another string here so for example a ferrari and now if we run this you can see that it will print ferrari because that is now at the index of 3 so otherwise it would crash if we wouldn't have added this item here but since we did the list actually has the index three and then we can print it afterwards but what if we actually wanted to print all of these items in our list one after another and that's where loops come into play there are two major types of loops the while loop and the for loop in kotlin and loops will just execute a specific action several times in a row so let's start with the while loop let's use a while loop to print out all these items we do that by writing while parentheses and in these parentheses we need to put a boolean condition that must be true or at least as long as this is true the while loop will repeat a specific piece of code so what i will do here is i will define a counter so var counter and set that to zero because our indie says start at zero and this also must be a var here because we want to increase the counter so we want to change the value of that later and as long as this counter is less than our shopping list.size so that is equal to the amount of items we have in our shopping list then we want to execute this piece of code so it will check if the count is less than that then execute that code after it executed that it will check again if the counter is still less than that it will still execute that piece of code until this condition starts to become false then it will jump out of that while loop and continue with the code afterwards so what we want to do is we want to print a line with the shopping list at the index of counter this time so this counter starts at zero and we just increase this counter in each iteration by writing counter plus plus so that is actually just a short way of writing counters equal to counter plus one we can just write counter plus plus and that will just increase that variable by one so we'll just start with counter equal to zero for the first index of that list then it will print that first index it will increase the counter so in the next iteration this counter will be one so we will print that item instead then we will increase it again so we print that item instead and so on and so forth so let's actually just remove this print line statement here and run our program and take a look in the console so now you can see it prints all the items in our list as expected but actually there is a much easier way to achieve the same behavior here and that is by using the other type of loop so for loops let's remove this loop here and write four instead parentheses and now with four we can simply just loop over the whole list so we can directly get references to the single items of that list so we can use for now we need to define a name for each item so shopping item for example for each shopping item in our shopping list we want to execute this piece of code and that is actually very readable in my opinion so a shopping item will actually start with lamborghini then in the next iteration it will be penthouse then rolex and so on so we just go through each item in our shopping list and now we can simply print that item so we just want to print a line with the shopping item and if we now run our program again then you will see it is the same result as before and there's also another feature we can use with for loops so let's remove that for loop again we could loop over a so-called range so that is just a range of numbers or of letters or whatever you want so for for example i which is usually a name for counter variables in programming for i in and now we can specify a range of numbers so for example from 1 to 100 that will just assign the values 1 2 3 4 5 and so on to i and execute this piece of code 100 times so if we would now print i and run our program then you will see that kotlin will print a hundred numbers here to our console and that are already the basics for loops in kotlin and the next thing i want to show you is the so-called when expression so we can create a val x here and set it to 3 for example now we can use a when x open curly brackets here and that is very similar to if conditions actually just in some scenarios a shorter way to write that so for example we could check if x is in the range of one to two then we make this arrow and let's say in this case we want to print a line x is between 1 and 2. and then we could just add another statement here if it is in the range of 3 to 10 for example then we want to print line x is between 3 and 10 and for example else so in all other cases if these two were false then we just want to execute another piece of code so if you want to make if you want to write more lines of code then you can also make these curly brackets here again you don't have to write that in a single line as i did here so just to show you that we could also write print line here x is not in the range of 1 to 10. and if we would now run this and then check the console you can see we will get the result axis between 3 and 10 which is true because x is 3 and that is as i said very similar to if conditions just in case you want to make all your if conditions depending on a single variable so depending on this x for example here then this one expression is actually a much shorter way to write that instead of writing if x is equal to this else if equal to this else if equal to this else and so on um that is just a more beautiful way to write that actually a better coding style now let's get to a very important topic which are functions so i will actually remove all of our code here in our main function so that is already a function that we created here but we had to create that to specify an entry point for our program but we can also create our very own functions that just do some stuff for us and then we just need to call that function name once in our program to execute the whole code of our function so let's for example create a function down here and that is done outside of the main function and we call this print 10 numbers for example so just a function that will print the numbers one to ten we will just use a for loop for that for i in the range of one to ten we want to print i and that is as you can see the same syntax as we had it for the main function just the function keyword the function name which also should start with the lower letter and then the rest in camel case parentheses why we actually have to do these oops i will explain soon and in this block of code here we just put the code that should be executed when we call that function and we can actually call that in our main function so that is still the entry point of our program by writing print 10 numbers and if we now run our program then you will see that it will actually print 10 numbers and such functions are of course very useful if you have a piece of code in your program that you need at very many places in your program because you don't want to write the same for loop here at every place that would just increase your lines of code by a lot and make it very messy instead you just define a function so you just need to call this function a single line to execute this piece of code over and over again and of course in bigger programs these functions can become very big as well so why do we actually have these empty parentheses here the reason for that is we can use these to specify parameters for our functions so if our function would rely on outside input so for example if we would want to give a value that we only have in our main function to our print and numbers function then we could do that in these parentheses here and let's actually specify another function here let's make it up here um that just checks if a number is actually an even number so for example function is even and now we of course need to pass the number to this function we want to check if that is actually even so we just type number colon and here we need to specify the type of that number so this time this is not optional which is an integer number and then we can open this function body with these curly brackets again and now inside of this function we can access the function that we pass as a parameter but this function should actually also return something because we passed this number from the outside and we want to check if that number is actually even or not and then we also want to be able to get the result of our is even function from the outside so we want to know if that is actually an even number or not and that is where so-called return values come into play so our function can actually return something so we give it some inputs in this parameters list here and our function just does its job and then gives us the output and we can specify the output after these parentheses here by writing colon again and the type we want to return here so in this function we want to check if the number we pass as a parameter is even or odd so we can simply return a variable of type boolean here because either this number is even or it's not even so either true or false and to actually return something in our function we use the return keyword and what do we actually now want to return well now we want to check if this number is even and if you remember correctly we can use this modulo operator i showed you at the beginning of this course so we could check if number modulo 2 if that is equal to zero so we divide our number by two and if the remainder of that division is equal to zero that means our number is divisible by 2 and that means it is even so to actually be able to use that function we go into into our main function again and now we actually want to be able to save the result of this is even function in a variable so because that returns a boolean we can save that boolean in a variable so for example a val x again and set that equal to is even so our function and this time you can see if we press ctrl and p then it displays the parameters we need to pass this time we need to pass a number so the number we want to check if that is even or not and let's just check for example if 5 is an even number which it is not of course so that will just check that if 5 is an even number and the result of that function so the boolean will be saved in that x variable here so afterwards we can simply print a line with x run our program and it will tell us if the number five is even or not and you can see it prints false which is of course what we expect here and by the way you could also just write several parameters in here so if you have more of these then you can just separate these with a comma so for example we could have a second number here which is also of type integer but in this function here this wouldn't make much sense in kotlin we are also able to use so-called default parameters that means we assign default values to these function parameters and then we don't have to pass a value for those so you can see when we call this function we pass the value 5 to it but with default parameters we can specify a default value and we can do that by simply setting that number equal to anything for example equal to 10 and that will use the value 10 for that number parameter if we don't pass a parameter for that number so in our case this wouldn't change anything because we call this is even function with the parameter 5 but in this case because we specified this default parameter here we could also leave the 5 away and this would also work in this case since we didn't provide a parameter on our own it will just use the 10 by default so this will just return true because 10 is of course an even number and for readability we could also use so-called named parameters and that means if we call this function here our is even function we can explicitly specify the name of this parameter we want to assign something to and just set it equal to any number here in this in this case so we use number is equal to let's say 5 again this is optional you don't need to do that but as i said that just improves readability a little bit so if you like to do that then you can do that and another very kotlin specific feature here are so called extension functions so those will be functions that extend an already existing type so for example integer string or whatever you like and that is really a feature that not many languages have but kotlin does so let's actually create a function an extension function is odd to check if a number is odd by simply specifying a function again so the keyword for that and now we want to specify the type we want to extend in this case it's integer because we want to be able to call that function on integer numbers and after that we write a dot followed by the function name so is odd and this time this function doesn't take any parameters so for is even we needed this number as a parameter but this time instead we use the number we call that function on and it will get clearer soon when we actually use that function so it will still return a boolean whether this number is odd or not and this time it will return because now we don't have that number we can refer to instead in extension functions we use the keyword this so this will actually be a number here and we can use this modulo 2 is equal to 1 this time because this time we want to check if the number is odd and now to call this function we can for example specify an y variable here set that to 3 and then print y dot is odd you can see now after after we wrote this integer variable first and wrote a dot after that we can now call this is odd function on that and that is just a different behavior as for this is even function but in the end it's the same okay so the next big topic i'm going to explain here are so-called classes classes really help us to structure our code better make it better understandable for us and also for others and in general a class is just a blueprint for something and if we want to create such a class we usually do that in its own kotlin file so outside of this main.kt file we want to go to our src folder right click on that and create a new kotlin file or class and i will simply create a simple animal class here because i think that is very good for educational purposes we select class here so we'll make sure that you have class selected and then press enter okay what can we now do with this class well we could give it some properties we can think about which properties or which characteristics does each animal out there have for example each animal has a name and then we could specify parentheses here and in these we could specify a val name which is of type string and now it's actually important to understand the difference between a class and an instance of a class so this what we did here was a class or is a class so we just specified each animal needs a name but an instance of the class is basically that blueprint applied so you can think of that if you buy a table then you will also get a manual that describes to you how you can build that table how you can construct that and that manual is the actual class and that table that outcome is an instance of the class and that's also what these parentheses here are called for classes that is the so-called constructor because whenever we construct such an animal so whenever we create such an instance we need to specify a name for that animal and let's actually switch back to our main.kt file and create an animal here remove this code and for example create a doc and we set that equal to animal and now in these parentheses you can see we need to specify a name for that which is just dark and what we could do now is right now nothing would happen here we could instead go to this animal class instead of this class body these curly brackets and specify a so-called init block so that is a block of code that will be executed whenever we create an instance of this class so here we actually create such an instance and for this animal for this dog here we will execute this init block and we could for example just use print line here and print hello my name is and then simply insert the name that we passed here when we constructed that animal so that will be dark here and if we now run our program and take a look in the console you can see it prints hello my name is doc but the really cool part about classes is now if it comes to inheritance because that is possible that we can define a class hierarchy and that some classes inherit from other classes let's actually do that and create a new class in our src folder new column follow class and now i will create a class only for docs so call that dog select class here and to specify that this class now inherits from animal because each dog is an animal we write a colon after that class name followed by the class we want to inherit from so animal and call the constructor on this animal so when i say call the constructor i just mean write these parentheses and specify the parameters we need to construct an instance of that class so now we need to specify the name for each dog we have and that is just dog and right now we get an error here because if we want to inherit from a class we need to define that class that we want to inherit from so our animal class as a so-called open class and then you can see that error goes away but what is this inheritance stuff actually useful for so you can see in our animal class we defined that name property here and for example we could also specify another property for example for the amount of lags this animal has so lag count which is of type integer of course and let's set that to 4 by default and then you will see now if we take a look at our doc class and for example use the init block here as well that we have access to the properties we defined in the parent class so in our animal class so if you write lag count you can see we have access to that variable even though we didn't declare it in this dark class but since we did declare it in our animal class and our dog class inherits from animal that means our dog class will also have all the properties that this animal class has and that means we can also access the lag count here but i actually want to remove this init block here in our dark class again and instead what we can do is we can also create functions in these classes so for a dog we could for example create a function to bark because not every animal can bark but each dog can bark so we don't specify this function in the animal class instead we specify it in the dark class and here we can just print a line wolf like this and now we can only use that function if we explicitly created a doc but not if we um created an animal so let's actually see how that works in the main function here in our main file here we created a dog but right now we set it equal to an animal but let's actually specify that this is equal to a dog now because we have that dark class and now this parameter is invalid because we already said that in our dark class here when we called that animal constructor here here we already said that each dog must have this name dog so we don't need to specify it here and now we can use that dog and bark so let's try that run our program take a look in the console here you can see first of all it will print hello my name is dog because it will still go inside of this init block of the animal class but then we call this bark function and it will simply print woof and let's actually also create such a class for for a cat just for practice we go to our src folder right click new cotton follow class call that cat select class and press enter this will also inherit from animal and this time we give it the name cat and we give it a function meow this time so we simply print a line and print meow and then we can go back to our main kt file again and also create a cat here so valcat is equal to cat and then we can use cat.meow so on this cat object we don't have the possibility to bark and the other way around we don't have the possibility to meow on a dark object and that just lets us model real-life scenarios really well in our program code which is usually pretty abstract so if we now run this you will just see what we expect here first of all um the dock will print its stuff and then the cat but right now we have the problem that we can also still create an instance of an animal but actually we don't want that because in nature nothing is just an animal everything is just a specific animal so we can only we only want to be able to create dogs cats but not just an animal and to fix that in our code we just need to go into our animal class and make that not an open class instead we make it an abstract class and that just forbids it for us to create instances of this animal object so if we go to our main file again and would try that again val nml is equal to animal then you see we get an error here cannot create an instance of an abstract class and these abstract classes are mainly just used to to just um model behavior that we want to have in the subclasses so of the classes that inherit from this animal class cat and dog but we don't want to be able to create an instance of an animal and we can also use this abstract keyword to create functions we just want to have in the subclass so for example you can see in in both of our cat and dot class we have a function that actually makes a sound from that animal and only the type of sound differs but not that both these animals can make a sound so what we could do is we could define an abstract function here make sound and we don't implement this function here we don't give it a body because it is abstract and in our cad and dot class you can see we get an error because now cotton wants us to implement this function in the subclasses so whenever we make a function abstract the classes that inherit from that class so cad and doc must implement this abstract function but they can implement it in their way so we could simply remove this and this would be an override function this time because we overwrite the behavior of the parent class and we call it make sound and then the error will go away and we can still specify for the cat that it will make meow and for the dog that it will make wolf so if we use override function here as well make sound and we really have to give it the same name as we did it in our parent class otherwise this won't work but right now we just model the behavior that every animal needs to have a function that makes a sound and in each class that inherits from animal we just give this function an implementation to specify how this specific animal makes its sound okay and as a really last thing about classes i want to show you here are so called anonymous classes so those actually allow us to kind of create instances of abstract classes so they don't really create that instance but we can create a temporary version of a class by using anonymous classes so we don't have to create that anonymous class in its own file instead we can go back to our main kt file remove this here and for example let's say we only we want to create a bear but we only want to be ex want to be able to access that bear inside of this main function and we don't need it anywhere else in our program then we can make that bear by using an anonymous class and that can be done by creating a val bear is equal to object colon so with this we basically create a temporary object of a class so temporary class kind of that inherits from animal and you can see now we need to specify the name for that animal again let's give this a name common bear and afterwards we open curly brackets again just as we did it for the other classes as well but since animal contains an abstract function make sound we also need to implement this function inside of this anonymous class here so we can simply type make sound and intellij is smart enough to suggest that we can simply press enter and it will auto complete that and then we can simply write a print line statement in here with raw and if you have problems understanding all that class stuff as a beginner then really don't worry that is not an easy topic here that just gets clearer over time if you apply these principles on your own but i just find it important to just mention that these topics exist but of course i can also not go into too much detail in this rather short crash course okay so next i actually want to talk about so-called exceptions what are exceptions in kotlin those are basically events that occur before or when our program actually crashes so let's actually remove this to clarify that a little bit if you think back to when we actually accepted user input so for example we have a variable here called number and we set that equal to readline and in case that readline return return function returns null we want to set that number to zero as a string that is nothing new for you but if we use that number and convert that to an integer then what actually happens if what we enter is not a number or is not convertible to a number so because readline takes in a string that means we could type anything in there and if we would now run this and take a look in our console then it will expect a user input by us so if we type number everything is fine but if we write hello for example then kotlin of course doesn't know how to convert hello to a number so if you now press enter you'll see that our program will crash and it will throw an exception you can see number format exception for input hello because it doesn't know how to convert this hello string to a number and of course if we work on a real project then we want to prevent that our project or that our program can just crash because the user entered a number incorrectly that wouldn't be good so how can we actually prevent that and the answer is with so called try and catch block so with that we can simply specify something that we want to try so in our case we want to try to convert a number to want to convert a string to an integer rather and then we will have a catch block where we can catch an exception so in case such an exception for example this number format exception occurs during this conversion from string to integer then we can catch that exception and execute another piece of code that we for example can display that the user entered a string that is not a number so let's see how that works we could write a val here and call that for example parsed number and we set that equal to try press enter here and in this drive block we now specify what we want to try so we want to try to parse our number that the user input entered in the command line and we want to convert that to an integer so if this succeeds so if this number is actually convertible to an integer it will just assign the integer number to the sparse number but if this fails we instead go into this catch block here and here we can specify an exception so e colon of type exception we choose this cotton exception here and press enter and in here we can now specify a value that should be assigned to this parsed number instead so in case this number is not convertible to an integer we will just assign another number to this parse number so for example just zero in case this succeeds we will just pass the the parsed number to this parsed number so the actual converted number and if this fails this integer conversion we will assign this 0 instead and if we wrote print our parse number afterwards and run our program take a look in our command line here it now expects an input of us so for example we could type 5. if you now press enter you will see it just prints out whatever we entered here so 5 is a number it is convertible to an integer but if we run this again and we type something invalid for example hello again and press enter this time it doesn't crash instead it will simply print out zero because it jumped into this catch block and assigned the zero to this parts number instead okay and as a really last topic of this course i want to give you a small introduction to so-called lambda functions and generics and that is really not a topic that i can fully cover in 10 minutes so if you don't understand that in detail right now what i will do then don't worry about that it will just get much clearer if you gain experience with kotlin those are not easy topics but i still want to show you what is possible with kotlin and how you can actually use that so first of all lambda functions what are lambda functions those are functions that we pass as a parameter to another function and now intuitively you might think why would i ever need that and that is pretty useful actually so if we remove that there are some predefined number functions in kotlin that we can use for example if we create a list val list is equal to list off let's put in some strings here kotlin comma is comma fun then what we could do is we could now count elements in this list according to a rule that we define on our own using a lambda function so that means we could write val count is equal to our list dot count and you can see this is a count function here that ends with these curly brackets and those are lambda functions in kotlin so what this means actually is it will go through this list here we created and count how many elements we have that fit to the rule that we will define here so you can see we have access to a string here which we can reference with it or we could also give it a name for example current string and then make this error afterwards and now we can reference that current string this function is currently going through and it will go through all of our strings in our list and we can we have to return a boolean if this function should return true or false for a specific string in this function and if it returns true it will count it so for example we can just count how many strings do we have on this function that have the length three so that have three characters and we could do that by writing current string a dot length which just returns the amount of characters a specific string has is equal to three so that will just as i said go through this list and count how many strings we have in this list that have three characters and if we would now print that to print that so print line count and run that program take a look on the command line then you will see it will simply print one because we have one string in our list function in our list here that has the the length three which is fun here and in lambda functions we always just return the last line of this lambda block so it's not the same as we did here with that return statement we don't write return this instead we just leave this expression as it is and the last line will be returned to this lambda function so what we did here is we just passed our very own function here with this block of code that affected the outcome of this function and if we now want to create our own function our own custom count function for example let's just write a function that does the same but just to show you how we can do that on our own we want to create the function here that extends this list type so an extension function that extends lists of string dot custom count and now as a parameter that will take a function so function and this function is of type now it's becoming a little bit difficult so first of all we need to specify which type of parameter this function takes so this function we pass as a parameter here we'll take a string as a parameter so we just write a string in here in these parentheses and that is the same string as we have here so we will just loop over this list here and count all the elements for which this function we pass as a parameter returns true so to actually specify that this function needs to return a boolean we use this arrow and specify the return type of that and now our whole function here our whole custom code function should of course return how many elements we did count so that is an integer number and we specify that by simply writing int and in this function we can now take our list which we can ref uh reference with this since this is an extension function the same way as we did it here and we first of all want to create a counter so how many elements we actually counted in this list so far then we want to use a for loop to loop over this list so to loop over these items in this list the strings so for each string in this because this is now our list that we call this function on and for each string in this list we want to check if the function we pass as a parameter actually returns true so if function which will now take that string that we are currently at so we pass that as a parameter if that returns true so since that returns a boolean we don't need to make any comparison here that is a typical beginner mistake that you just compare that to true but that is not necessary here we can just leave that away and then we just want to increase the counter by one and in the end of our whole function we return our counter so i will go through that one more time because i'm sure that is super confusing if you're a beginner we extend the type a list of type string so we extend the type of lists we have up here we call this function custom count which should just do exactly the same as this predefined count function just that you see how we can create our own function that serves as a lambda function we pass this lambda function here as a parameter so the parameter is of type this is how we specify a function type so this function that we need to pass as a parameter takes in a string as a parameter which is equivalent to this string here and it returns a boolean which is equivalent to this expression so this also either returns true if the current string has the length three or it returns false if it does not have the length three and this whole function or a custom count returns an integer which is the amount of items we counted for which this function was true and in our custom count function we just have this counter variable that we set to zero initially and we just go through all of our strings that we have in this list and if we find a string for which our lambda function that we pass as a parameter returns true we simply found such an item we want to count so increase the counter by one and we could now simply replace this predefined count function with our custom count function and it would work exactly the same so for example we could change this a little bit we could make this greater than or equal to three and that should now return two because we have two strings that have three or more characters and you can see that is exactly what happens here and if we now want to be able to call this custom count function on any kind of list not only on a list of strings then we use so-called generics and that is basically just a type parameter so we pass the type we want to call this function on we can do this with these angle brackets and usually we just call this type t so a capital t and then we can use that t so whatever we passed for that also in this list so instead of string instead of this string and that's already it so we just um call this function here we extend a list of type t so just a list of any type and then we have access to that type in this function so this would now also allow us to call this custom count function on the list of integers on a list of characters of floats of whatever and that is of course what we want to be able to do we want to be able to call this on any type because the type doesn't matter if we want to count the amount of elements we have in the list but that is it for this crash course congratulations that you followed through this long and really as i said don't worry if you didn't understand all of it and that is normal especially the stuff that we um worked with at the end of this course so classes lambda functions all that stuff there is much more depth into this topic actually so you can go much deeper into these topics and it's just not enough time to fully cover these in a crash course but it's also not necessary to know them in in its full detail as a beginner because in my opinion you will just gain experience while coding and the details you will actually learn on the fly so if you ask me personally what you should do next is i would always suggest just to practice what you learned in this course because just by watching you will learn nothing at all so you really need to do something on your own to really learn something and yet just write little functions for example a function that finds an item in a list and returns the index of it a function that reverses a list a function that checks if a specific number is a prime number and all those little functions that are not too difficult but challenging as a beginner if you are able to do these then you will have some feelings of success and really don't mind if you liked my way of teaching to check out my channel phillip luckner i do all kinds of stuff currently only using kotlin so you can really learn more detailed stuff here than i could cover in this crash course and also if there is anything you think i can improve on my way of teaching then i would also love to hear about that in this video's comments so thanks everybody who watched this far and again thank you brad for giving me that opportunity to just teach my favorite language kotlin and i wish all of you a very nice day
Info
Channel: Traversy Media
Views: 84,655
Rating: 4.9338603 out of 5
Keywords: kotlin, learn kotlin, kotlin crash course, kotlin tutorial, kotlin programming, kotlin for beginners
Id: 5flXf8nuq60
Channel Id: undefined
Length: 83min 49sec (5029 seconds)
Published: Mon Nov 09 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.