Kotlin Course – Tutorial for Beginners

Kotlin Course – Tutorial for Beginners
Spread the love

hi    my name is nate and welcome to this    tutorial on the kotlin programming    language    if you’re not familiar kotlin is a    statically type programming language    developed by jetbrains it’s been around    since about 2011 and has steadily    increased in popularity ever since today    it’s actually the primary development    language for android and in this    tutorial we’re going to move from basic    topics like setting up your first    project up to more advanced things like    modeling data and working with higher    order functions    the goal for this tutorial is to help    you understand how to work with kotlin    so that you can then take that knowledge    and apply it to building applications    across mobile web and native code so    without further ado let’s jump in and    start building our first kotlin project    the first thing we’re going to want to    do is to install jetbrains ide intellij    so that we can work with our kotlin code    on our development machine    now the first thing to do is to open up    your browser    and search for    intellij here you should see a download    link and we can click on that to be    taken directly to the download page    now i’ll be working on a mac but    intellij is available on windows and    linux as well    you’ll also notice here that there are    two different versions of intellij    there’s the ultimate edition and the    community edition the ultimate edition    has a lot more features that we need and    there’s also a paid product the    community edition    is supported for jvm development and    android development so it’s perfect for    what we want to look at in this tutorial    when you’re ready go ahead and click the    download button and that should start    the download    once the download is complete we’ll get    started on installing the ide and we’ll    take a look at hello world in kotlin    now that our download’s complete we can    go ahead and launch the installer    and on mac we’ll drag the application    into our applications folder    which will    start the install process here for us    once the files have been transferred to    your machine we can go ahead and start    intellij for the first time to start the    install process    in this case we want to do a fresh    install so i’ll click do not import    settings and hit ok    go ahead and accept the privacy policy    hit continue    now here you can choose your theme i’ll    choose the dark theme    go ahead with the standard intellij key    settings here    and we’ll go ahead and click next    through to finish the setup process    and then we’ll finally launch intellij    ide community edition    the next thing that we want to do is    create our first kotlin project here in    intellij    so to do that we’ll    click on create new project    now over on the left side of this panel    we’ll see a number of different project    templates to choose from because we are    going to be learning about kotlin we    want to make sure that we have selected    the kotlin template    now within this there are a number of    different kotlin project types that we    can choose from the default here at the    top is a kotlin module for a jvm target    so this would be sort of a standard    just kotlin project that could target    the jvm    nothing else added to it other examples    would be you know kotlin module for a    javascript target or a kotlin native    target    or an android or ios mobile target    so all of those are interesting but more    advanced    for this we want to just stick with the    basics so we will make sure that we have    selected kotlin module for jvm target    and go ahead and hit next    then we want to make sure that we name    our project something meaningful so in    this case let’s call it hello    kotlin    we’ll make sure that our project    location is set    and then we’ll go ahead and select    finish    now we have an empty kotlin project    let’s start by adding our first copman    file so that we can write a simple hello    world example    so to do that we’ll come over here to    the left and here we have the project    panel within intellij    you’ll see at the top we have our hello    kotlin module    if we expand that we can see that we    have a source directory but it’s    currently empty    let’s right click on source    go to new and then kotlin file or class    and here we’re going to type main for    the name of our file and then we will    leave this as file so that we can create    our    main.kt file    now we can get started by writing our    main function here in our main.kt file    so to start we’ll type    fun    main    no parameters    and then we can type    print ln    parentheses    hello    kotlin    and from there you’ll see now that we    have this little green arrow    intellij recognizes that this is an    executable main function within this    hello kotlin module so we can actually    go ahead and run this    we’ll select run main kt    and that will take a second to go ahead    and build the project and then we will    get our output window here at the bottom    and you can see that we have hello    kotlin    now one extra quick fun fact here    intellij comes with a number of live    templates built in    this means that you can type something    and it will know how to complete that    and auto-generate some code for us so we    can start typing main    and then hit enter    and it will automatically generate a    main function for us and then we are    free    to fill in    with our    hello    kotlin text    awesome you’ve just written your first    program in kotlin now let’s dive in and    start actually learning the language    to get started let’s look at how you can    define variables in kotlin    now there’s two types of variables in    kotlin    we can define    mutable variables which can have their    values reassigned    those are declared using the    var keyword    or we can define    local read-only variables which can have    their value assigned only once    these are defined using the    val keyword    so to define a variable    we can use the keyword of our choice so    in this case we use val    then we’ll define the name    and then we need to indicate the type    in this case i’ll say a type string    and then you can use an equals and then    you can assign the value to this    variable so in this case i’ve defined a    variable called name of type string    and then i’ve assigned the string    literal nate to that variable    now like i mentioned val are assign    once variables meaning this is read only    once it has a value assigned to it so if    i try to update the name of this we’ll    see that we get an error    that area says val cannot be reassigned    so this is our indicator that if we need    to be able to update the value of our    variable we’re not going to be able to    use a vowel    instead    we could use a var now var variables    can be reassigned as many times as you    want so as soon as i updated that    keyword now i can update    the value of our name variable    and then if we want to use that variable    we could pass that in to the print    function here    and if we then    run our main function    we’ll now see the output value of that    variable at this time is blank because    we’ve reassigned it    if we    remove that reassignment    we’ll now see that we get this little    underline saying variable is never    modified and can actually be declared    immutable instead using val    so this is nice that the ide gives us    that helpful hint so in this case we’ll    go back to a val    and now if we rerun this once again    we’ll now see that my name was printed    out to the console    in this example we’re using a local    variable meaning that    the variable that we have defined is    available locally within the current    scope so in this case it’s available    only within the main function we have    defined    now in kotlin you can actually declare    variables outside of any type of    enclosing function or class    all you have to do    is declare    a variable within a kotlin file    so in this case we’ve moved our variable    name outside of the main function into    the main.kt file    variables defined like this are referred    to as top level variables    and you see now that we’ve moved this    outside of the main function    we can still    run it    and our variable is still completely    valid    top level variables can be worked with    just like a local variable    so we could define an additional    variable this time we’ll say var    greeting of type string equals hello    we now have a publicly available    top level variable called greeting    so now if we wanted to come down here    and print out a greeting before the name    we could do that    by calling print line and passing in    greeting    we can also    modify    that greeting    because this is a mutable variable    and if we then print out this new value    we will see that    the message has changed    so when we hit run here we should now    see    hello nate and then highmate    let’s take a closer look at how variable    types are defined    so in defining our variables in both    cases we use either the val or var    keyword    and then we have the variable name    both of these are must haves    next up we have the colon and then the    type so in this case we have the type of    string    and then we assign our value    one interesting difference between java    and kotlin is that types in kotlin are    non-null by default    this means that there is a distinct    difference between    string and a nullable string    now what does this look like in practice    well in this case because types are not    null by default name is a non-null    string    so if i try to assign    a null value to this will actually get    an error and it will hopefully say null    cannot be a value of a non-null type    string    so if you want to actually have null as    a valid value for your variable you need    to add a question mark    after that string value    this indicates that now name is a    nullable string and i can assign null    or i can go ahead and sign an actual    value    so let’s look at how we could use this    with the greeting variable    so if we make greeting a    nullable variable we can come down here    and we’ll go ahead and print out the    default greeting value we’ll print out    the name    and then we’ll see that we can modify    the value greeting to null    and then we can go ahead and print out    these values once again    and we can then see that greeting has    been updated and when we try to print    that out it actually recognizes that    it’s null and prints that out to the    console for us    so let’s look at how we can actually    simplify the declaration of our    variables    i mentioned that val or var    as well as the name are mandatory    however kotlin supports type inferences    on variables and properties what does    this mean well this means that kotlin    can recognize what type the value is    that we’re trying to assign to the    variable and if it can figure that out    we can actually omit the type    declaration of the variable    so in this case    we could actually    remove the colon and string    and    the name    variable    will still be of type string    now we can do the same for our greeting    variable    so we can    remove this    but    if we come back down here and try to    assign null to greeting we’ll get an    error no cannot be a value of non-null    type string    so why is this    well again because types are non-null by    default in kotlin    and we are assigning a    non-null string literal to greeting the    compiler infers that greeting is meant    to be a non-null string    so    if you want to have a nullable string    you might try    and just assign null    however    we get a warning saying implicit nothing    type this is because greeting now cannot    really be inferred it doesn’t know what    it is a null type of so in this case    we will need to go ahead and specify a    nullable string    now down here we can assign null to    greeting    or we could assign    an actual greeting    now that we’ve taken a look at how to    create variables and how the type system    works    let’s introduce some basic control flow    and we’ll do this by working with the    nullable string variable of greeting    so let’s go ahead and remove    these values    now let’s say that we only want to print    out the value of greeting if it’s not    null    so we could do that in a couple    different ways the first one we’ll look    at is using an if statement    if statements in kotlin work very much    the same way as in java so we’ll use the    if keyword    followed by parentheses    we use greeting in this case we want to    say if greeting is not null print it out    so we can say    not equal to no    and we’ll finish it off with curly    braces    and then if we    move our print statement within that if    conditional    when we run this    we should now have no greeting printed    out and sure enough we see that just the    name is    printed and if we    modify the value of greeting to be    non-null    and then re-run this    we’ll now see that we have our greeting    now what if we wanted to add an    else clause    so    just like java we could add else    we can add curly braces again    and so here    we could define a default greeting of hi    so now    if we run this once again greeting will    be null and so we should see the default    high value    now another means of control flow within    kotlin    is the when statement the when statement    is very similar to a switch statement in    java    so to create that we can come down and    use the when keyword    and then parentheses    we then want to pass into this the value    that we want to check and switch on    depending on its value    so in this case we’ll pass in greeting    followed by curly braces    now within this block we can define    each    value that we want to act on differently    so in this case we can say    null    and then to define what action to take    we use    an arrow    and then we’ll say    print line    hi    and then we can define    an else case here and this will act as    the default if none of the values above    are matched so in this case    we will print out the value of greeting    on its own    so now    if we run this    we should see hi printed out because    greeting is still null    and once again if we update greeting    to be some other value    and rerun    we’ll see that the else branch of the    when statement is hit and we are    printing out the value of greeting    so these are two of the basic ways in    which you can manipulate control flow    within kotlin now we just saw how if and    when can be used as statements to take    different actions based on some checked    value    if and when can also be used as    expressions to assign a value depending    on those logical conditions so let’s    take a look at how we could use an if    expression to assign a value to a local    variable    so let’s go down here    and type val    greeting    to    print we could say equals    now if the greeting variable in our top    level declaration    is    non-null then we want to go ahead and    stick with that so we could say if    greeting    does not    equal null    then we want to assign    greeting    to the new greeting to print variable    otherwise    we want to    say hi    and then we’ll update    our print line to use the local variable    now when we print this out    we should see the else branch of high    being printed out    this is because the top level variable    is currently null    if we    modify this    to pass in a greeting    now    if greeting does not equal null we’ll    return true and we’ll see that hello is    printed out instead    so if we want to assign different values    to a variable depending on whether or    not something is null or some other    logical check we could use an if    expression    however    we can also use a when expression if we    want it so we could say    when    and again we’ll pass in reading here    and    again we’ll use our null value as the    first check    and if it’s null we’ll go ahead and    return high    otherwise we’ll go ahead and return the    original greeting value    so now what this when expression is    saying    is assign    the value of high to greeting to print    if greeting is null    and likewise if greeting is non-null go    ahead and assign that value to the new    greeting to print variable    so    if we run this one more time    we should see hi because greeting is    null    and if we assign a value to greeting    and re-run we’ll see that updated value    of hello    so again like the if expression a when    expression can be used to assign    a value to a variable depending on that    input value that it’s checking    to start understanding functions in    kotlin let’s look at this example    within this example we actually are    using two different functions we have    our main function and then we’re also    using the println function as well    so let’s take a look at how we can    define our own new function    we’ll start by clicking here    and we’ll define a new function that is    going to return the string that we want    to print out to the console    so the first thing to do when defining a    new function is to use the fun keyword    this denotes that we are going to define    a new function    then we want to specify the function    name    so i’m going to call this function    get    greeting    and then you want to follow that up with    open and close parentheses    and within this we can actually define    any function parameters now for now    we’re going to skip any function    parameters    and we want to define our return type    for this function    so similarly to variables we can define    a return type by using a colon and then    the type in this case string    and then we’ll do open and close curly    braces    now like in java we can define the    return value by saying    return    and then in this case i’ll say    hello    kotlin    so now we have a function called get    greeting that is going to return the    string hello kotlin    if we want to then    invoke that function    we could do so    by calling get greeting    with open and closed parentheses    this should look very similar to what    you’re familiar with in calling methods    from java    and now if we    run our code    we’ll see two print statements we’ll see    the first one hello world and the second    one hello kotlin    so one thing you may have noticed    is that in our get greeting function    we’re specifying the return type of    string    however in our main function there’s no    return type specified so why is this    well let’s illustrate this by an example    let’s write a function    called say hello    so again we’ll use the fun keyword    and then we’ll name it say    hello    no parameter values    and then we’re going to    declare this as returning type unit    unit in kotlin    is essentially the absence of any useful    type    it’s similar to saying this returns    nothing useful    and the reason we’re going to use unit    in this case is because we don’t want to    return anything we’re going to    simply print out    our    get greeting functions return value    so we can then call    say hello    and you’ll notice up here that    unit is underlined and it’s giving us    this message that says redundant unit    return type    basically what this is saying is that if    you have a function that returns unit    that is to say if you have a function    that doesn’t return anything useful    you can omit that type value    so we can actually    remove    unit from our say hello function    and this is perfectly valid so that’s    why in our main function we also don’t    have a return type specified    aside from the rules around unit return    types return types for functions work    very similarly to how you would define    them and treat them for variables or    properties    so for example if we wanted to return    a    null string from our get grading    function    we would modify the return type to be a    nullable string    and then we could return null    in our return statement    additionally    functions support type inference as well    so in our get greeting example here    we are returning a single    string literal in which case we could    actually simplify this to a single    expression    we could remove the curly braces    and add an equals and then the string    literal after that    so this is what’s known as a single    expression function because the entire    function definition is now in a single    expression    and now this is where the type inference    comes into play    again because the compiler understands    this single expression function    definition and it knows that it’s always    going to return a string we can actually    remove the explicit return type    now our get greeting function    is extremely simple    and is    functionally equivalent to the previous    definition    so if we run our code once again    we’ll see that we now have our three    different print statements you might be    noticing a theme here of kotlin allowing    us to reduce the amount of code we need    to write to get the equivalent    functionality this is a theme that will    crop up more and more as you start to    learn the language    now let’s take a look at how we can    define function parameters    now before we get started    let’s clean up our code a little bit    so we’ll remove everything from our main    function    and we’re going to go ahead and remove    the existing function examples we’ve    been working with    so once again we’re going to define a    function named    say hello    and to start    it will    print out hello    kotlin    now this is exactly like we have seen    before    but what if we wanted to change the    thing that we were greeting so instead    of saying hello colin maybe we wanted to    say hello world or hello nate or hello    john    so how might we do that well that’s    where a function parameter comes into    play    so    to define a function parameter    we’ll go within the parentheses after    the function name and we’ll define this    using a notation of the parameter name    colon the parameter type so in this case    we’re going to say    item    to    greet as our parameter name    colon and that we want this to be a    stream value that we’re passing in    now within our function    we could say    val    message    equals    hello    plus    i don’t you greet    and then we could pass in the message    now if we come down to our main function    we want to invoke say hello    so we can start typing say hello    and now we need to pass in a parameter    value which it suggests to us in this    little tool tip    so in this case we’ll say    kotlin    and now if we run our main function    we now see hello kotlin is printed out    to the console    if we wanted to print out something else    we could duplicate the invocation    and maybe this time we’ll pass in world    and if we invoke our main function again    we’ll now see hello kotlin and hello    world printed out to the console    now if we go back up to our say hello    function    we’ll notice that there’s this squiggly    line here    this is unrelated to function parameters    but this is a really interesting feature    in kotlin kotlin supports    string templates which allow us to    substitute in    variable values or argument values into    a predefined string template    so in this case instead of using    concatenation    we could say hello space    and then to define a templated value    we use a dollar sign    and then we can pass in the parameter    name    so now    if we hit run once again we’ll see the    same output as before so this is just    one more way in which kotlin can reduce    boilerplate for us by allowing us to    define these convenient string templates    in fact in this scenario we can take it    one step further and remove the local    variable altogether    and then we can actually take this one    step further    and define this as a single expression    function    now we have a say hello function    that will take in a parameter value    which is the item to greet and then it    will always print out hello item to    greet so now let’s update this to take    two parameters so that we can customize    both the greeting and whatever it is    that we want to greet    so to do that we’re going to add a new    parameter    and we will name this one greeting    and have it be of type string    and now we will update our stream    template here    to include that new parameter    awesome so now we’ve updated the    function now we need to update the    invocation of that function    so for this first line    we could say    hey common    and now for the next one we’ll say    hello world    and if we run this    we’ll now see our desired output so by    adding that second parameter value we    have now made our say hello function    much more flexible    now we can add any number of parameters    we want to say hello    but like any programming language if you    have too many parameters in your    function it might be an indicator that    your function is doing too much    now one last thing i’d like to point out    about functions at this time    is that you’ll notice that these    functions are not defined within any    type of enclosing class    these are    free functions or    as they’re referred to in kotlin these    are top level functions    like variables functions can be defined    outside of any    enclosing class or independent of any    associated class    now there are types of functions that    are associated with a class and we’ll    take a look at those later on in the    tutorial    like most programming languages kotlin    has support    for collection data types    these are things like arrays lists and    maps they can use to group values    together and then operate on them at a    later time    let’s start off by looking at how we can    define an array in kotlin    we’ll clear out these indications to say    hello because we won’t need them right    now but we’ll leave the sayhello    function definition because we’ll come    back to it later    to create a basic array we’ll create a    new local variable named interesting    things    and then we’ll use the equal sign and    then we can use a convenience function    called    array of    in parentheses    this will    create an array of whatever the inferred    type is    and then we can start defining values    within this function so in this case as    soon as i    add a string literal    it can infer that this is going to be an    array of strings    and now we can define some interesting    things like    kotlin    programming or    comic books    now that we have this variable defined    let’s see what types of operations we    can perform on it    if we start typing interesting things    and hit dot the ide will start to    auto-complete and show us some of the    methods available so you see we have a    size property    we have a    get method and we also have this open    and closed bracket    syntax that we can use to access    individual elements in the array    let’s try printing out some of these    values to demonstrate how we can use the    array to start let’s print out the size    we can do that by saying print ln and    then we’ll do interesting things dot    size    now let’s print out the first element in    the array we can do that by going print    ln    interesting things    we can use the open and close bracket    and then pass in an index    this is how we can conveniently index    into that array    this is similar    to doing a get    so if we duplicate that line we could    say    get    and again pass in the zeroth element of    that array    if we now run this    we’ll see three kotlin kotlin this is    just as we would expect now what if we    wanted to iterate over all of the    elements of this array    and then perhaps print out each of those    values    well there are a number of different    ways we could do that    for now we’ll take a look at a basic for    loop    so    we can start typing 4    and then we could say    interesting    thing    in    interesting things    then open and close curly braces    this is now the convenient syntax of for    loops within kotlin so this is going to    iterate over each value in the array and    we can access those values in the    interesting thing variable that we have    defined within this for loop so now    we can type out    interesting thing    and if we rerun this code    we’ll now see that we have    printed out each element in the array    so that type of for loop is what is    probably most similar to what you’re    used to if you’re coming from java    however in kotlin because we have top    level functions and    higher order functions really just first    class support for functions across the    board we can write code that is a bit    more functional so let’s take a look at    how we could do a more functional    approach to collection iteration    so we’ll remove our for loop    and now we can say    interesting things dot    for    each    and what this is    is invoking a    for each function that is available    in the standard library    that function then takes in another    function and returns unit    that function that we pass in    essentially defines what to do on each    iteration over this collection so within    our curly braces here this is where we    can define what we want to do with    each element in interesting things now    this might look a little bit confusing    at first but don’t worry we’ll explain    this but if we simply want to print out    each item in this array we can now say    print ln    and pass in it    it is the default name    for each element in the array that is    passed into this lambda function in    which we are defining    so if we run this    we’ll now see that we have our three    elements in the array printed out to the    console    now it is not always very readable so    another little quick tip here is if you    want it to be named something else you    can rename    that value that’s passed into the lambda    in this case we could call it    interesting    thing    and then we’ll use the arrow    and now instead of it    we can reference that value by calling    it interesting thing    and once again if we run this    we’ll see that our interesting things    are printed out to the console    you might be looking at this wondering    why we are not using an open and closed    parentheses when calling the for each    function    in fact it might seem rather odd    that we are not passing in that argument    to for each but instead have just    specified this open and closed    parentheses independent of the rest of    the for each call    so this is actually what’s known as    lambda syntax within kotlin    now we’ll look at how to implement this    later but the idea behind lambda syntax    is that if you have a function and its    only parameter is another function    then you can omit the parentheses all    together    and you can pass that function in by    specifying this open and close    parentheses    so again if we look at for each we’ll    see that it takes a single function as a    parameter    so    we can omit the parentheses values    and pass that function into the for each    function using the open and closed curly    braces    and like i said we’ll look at how we    actually define this type of higher    order function    a little bit later in the tutorial    so here we’ve looked at a basic for each    function on this array collection but by    doing it this way we’ve lost the index    data    for whatever index the current    interesting thing is in the containing    array so to handle that there’s another    function we can call so once again we’ll    say interesting things    and this time we’ll say for    each    indexed    now this time it’s going to pass into us    the current index    as well as the current string    now once again we’ll update this to be    named    interesting    thing    and now once again we can print out    these values so we can say    print ln    and we can say    interesting thing is at    index    and now if we    print this out    we’ll see that we have gotten the value    from the array as well as its current    index so this could be really useful if    you need to iterate and still maintain    that index data    now everything that we’ve been looking    at here for arrays is applicable for    lists as well    so if we clear out some of this previous    code    we now go to our declaration of this    interesting things variable now we’re    using the convenience function array of    to define this variable as an array of    type string    now there’s also a    list of function as well    now if we try to work with interesting    things we’ll see that we have a lot more    methods to choose from because it’s now    a list rather than an array and so like    an array we can access individual    elements    by using a get    or also    by using    the bracket syntax like we’re familiar    with with arrays as well    and also like with the array    we have functions available to us to    help with iteration so if we wanted to    print out all of the interesting things    again    once again we can say interesting things    dot    for each    and once again we’ll say    interesting    thing we’ll use the arrow here within    our lambda    expression    and then we’ll    print out    the interesting thing    and if we hit run voila we have our    three interesting things printed to the    console    now that we’ve looked at arrays and    lists let’s take a look at one more    collection type in kotlin which is map    let’s remove this iteration over our    interesting things variable here    now let’s create a new variable    and we’ll just name this map    equals and once again there is a    map of function that we can use    now the map of function    will essentially take in pairs    pair is a simple wrapper class    containing two values    and there’s also a convenience function    to create pairs so if you want to create    a basic key    value map we could do so like this    we use a key of one    and then we’ll use two    and then the value in this case will be    a    and then we’ll define another pair we’ll    use a key of    two then we’ll use the two    function    and then a value of b    and then we’ll define one more pair    and we’ll say 3 is our key    to    c    so what we’ve now done is defined a map    with three pairs of values in it the    keys are 1 2 and 3 and the associated    values are a b and c    now we can iterate over this by saying    map    for each    and it’s going to    return to us both the key and the value    unfortunately they default to a not very    useful name so in this case we’ll rename    them again within our lambda expression    so we’ll say key    value    and then we can    print these out and we’ll use a stream    template and we’ll just say    key    and then we’ll define an arrow just for    some separation and then    value    and now if we print this out    we’ll now see that we’re getting each of    our key and value pairs and then we can    do with those whatever that we need to    we’ve seen how you can define several    different types of collections such as    arrays and lists and maps and we’ve also    seen how you can iterate over those    collections and access individual    elements from a collection    and there’s an interesting thing to    point out about the way kotlin handles    the collections similar to the way in    which it differentiates between nullable    and non-null types    kotlin also differentiates between    mutable and immutable collection types    now what does this mean    this means that by default a collection    type in kotlin is immutable so that you    can’t add or subtract values from that    collection once it’s initially created    so let’s look at an example of this    we have defined our interesting things    list using the list of function here    and if we wanted to try and add    something to interesting things    there’s no function available to us to    do that    that’s because it’s immutable by default    if we wanted a mutable list    we could use the    mutable list of function    now if we want to add something we can    say interesting things dot    add    and we could add    a new string to our interesting things    list    the same goes for map if we wanted to    add a new key value paired to our map    we say map dot put    but there’s no put method available    but if we change to    mutable    map    now we can say map dot put    and we can define a new key of four    and a new value of d    so this is something to keep in mind    if you have a collection that’s going to    be static once it’s defined then you’re    fine to use the regular list of array of    map of etc functions    and that is a good thing because    immutability is often a desirable trait    in your code    however if you’re going to want to    modify the values in that collection    then you’ll have to create a mutable    collection so that you have access to    things like put or add that let you    modify that collection    now that we have an understanding of    working with collections let’s modify    our say hello function to take a    collection parameter so that we can    greet multiple things    we’ll modify first the name of item to    greet to    items to greet because it’s now going to    be plural because it’ll be a collection    and i will update from string to list of    string    and then now we’re going to update the    implementation of this function so    instead of being a    single expression function    we’ll add a function body    and then now we’re going to want to    iterate over the items to greet    parameter so we’ll say items to greet    dot    for each    and we’ll paste back in our original    print statement    and then we’ll go ahead and update    the    receiver value here from it to    item to    greet    it will add our arrow    and so now we have a say hello function    that you can pass a collection into and    then it’ll print out multiple lines so    now we can say say    hello    and we can still pass in our custom    greeting so we can say    hi    and then we could pass in our    interesting things variable    and now if we click run    we now see high kotlin high programming    and high comic books so this is just a    quick example of how you can pass in a    collection type    to a function as a parameter    there’s nothing wrong with including a    collection parameter in your function    however functions in kotlin do provide    an additional piece of functionality    that can satisfy this use case and    provides a little additional flexibility    now to demonstrate why    this might be interesting to us let’s    look at an example so let’s say we want    to call say    hello and we’ll pass in our greeting    but then we don’t want to pass in any    interesting things in this case    well because of the way that this    function is currently defined we have to    pass in the second argument so in this    case if we wanted to pass in    no items    we would have to pass in    an empty list    which isn’t really a big deal but it’s    also not the most flexible way of    handling things    so let’s take a look at an alternative    means of achieving this functionality    if we come up here to our say hello    function we’re going to modify this    second parameter so that it is a var arg    parameter    var arg is a keyword    in kotlin    that essentially represents a variable    number of arguments    so in this case    instead of taking a list of string we’ll    define a    var arg of string    this tells the compiler that we’re going    to take a variable number of string    arguments after the initial greeting    argument to this function    so now if we try    to pass    something in to say hello    we’ll first pass in our greeting    and now we don’t actually have to pass    anything in    after the initial argument    this is because    the var parameter will essentially be    treated as an array of whichever type    it’s used to specify so in this case    items to greet is now an array of type    string    so if we don’t pass any    items after the greeting    it will be treated as an empty array    if we did want to start to pass items we    could do that by separating them with    commas so we could say    kotlin    and now this would be an array of size    one    but where the real flexibility comes is    we can now start to define    many argument values here    and so now all of those arguments that    are passed in will be grouped together    treated as an array    and so in our function implementation we    can still iterate over all the elements    in that array    so if we now run this    we should get the same output as before    so by using our var arc parameter we’ve    eliminated the need to always pass in a    value after the initial grading argument    it lets us have greater flexibility    because it will support zero    one or any other number of argument    values to be passed in    now it’s very convenient to be able to    pass multiple arguments to this far art    parameter    however    you’re usually not going to be hard    coding those arguments in manually    during compile time more likely you’re    going to get a array of values from a    network request or a database and then    you’re going to want to pass those in    so    you might think that it would be as    simple as passing in an array after that    initial greeting so let’s try that    we can change list of    to array of    and then after our grading    we’ll pass in interesting things    uh oh unfortunately this does not work    and if you look at the error you’ll see    it requires string found array of string    so how do you actually pass in    an array of existing values    to this var arg parameter well you can    do that    with the spread operator and all the    spread operator is    is applying the asterisk    before the array variable    when you pass it in as an argument value    so now    if we hit run    we’ll see that the compiler is now    accepting    that array and we are iterating over    each item in that interesting things    array    so this is how you can pass in an    existing collection as a var arg    parameter    another really interesting and powerful    feature with kotlin functions are named    arguments now let’s take a look at    example of what named arguments provide    to us    we’ll start by clearing out our main    function    and we’re going to define a new simple    function    that will take a greeting and a name and    then print that out    so now when we want to call this new    greek person function    say greet person    hi    and then i’ll use my name here    now this is fine and it’s very easy to    understand because the ide is helping us    and showing okay this is the greeting    argument this is the name argument    however if you are in a code review    you might not be able to know exactly    which order these arguments are supposed    to be passed in    also if you wanted to modify the    function signature of green person down    the line you’d have to make sure that    these are in the same order    because since they share the same type    you could mix that order up without    getting any type of compiler error    now what named arguments allow us to do    is specify which parameter    this argument value is going to be used    for    so what does that actually look like in    practice well    it looks like    defining the name of the parameter    and then an equal sign    and then here we can say name equals    and so now we’re saying very explicitly    assign hi to greeting and mate to name    the cool thing that this allows us to do    is actually mix up the order    of    these arguments    so now we can actually pass the second    parameter first and the first parameter    second    so now we can actually theoretically    modify the signature of greek person    changing the order of these parameters    and it wouldn’t impact the invocations    of that function    kotlin allows us to take this    flexibility    one step further by leveraging default    parameter values    so once again let’s look at our greet    person example    so here we are now able to    pass the arguments in whatever order we    want    if we’re using named argument syntax    but what if we wanted to pass name first    and then not even pass in the greeting    well now we get an error because it says    no value passed for parameter greeting    so as greek person is currently defined    it must take    both    arguments    even if they are in a mixed up order    default parameter values allow us to    change that    it allows us to tell the compiler what    the default value should be if none is    specified    so for greeting    we could provide a default value of    hello    and for name we could provide a default    value of kotlin    you’ll see now    greet person can be called by only    specifying a single argument value    and if we run this    we’ll see it’s going to say hello nate    so it’s getting the default    greeting value and then it was using the    value for the name that we passed in    now because both arguments    have defaults we could actually call    this without passing any arguments in    and if we run it now    we’ll see it’s using both defaults and    prints out hello kotlin    now this becomes a really powerful    feature because now we can not only mix    up the order in which we pass arguments    but we don’t even have to pass all of    them in this actually allows us    to replicate functionality of the    builder pattern without actually having    to write getters and setters and have    private constructors and all of that    we can configure and reuse functions and    objects by leveraging    these default values and the named    argument syntax    while default parameter values named    argument    and var arg parameters are really    convenient and flexible and powerful    they do have limitations as well so i    want to illustrate one of those    limitations    so we’re going to go back to our say    hello function    let’s redefine our interesting things    array    so now if i want to invoke say hello    and i want to pass things in order with    the greeting    and then the interesting things i can do    that no problem and if i run this    we’ll get our three lines of output    and so now what if we wanted to use    named    argument syntax well we could do that as    well greeting equals hi    however as soon as i add the named    argument syntax to the first parameter i    get this error saying mixing named and    position arguments is not allowed    so this is one of those limitations as    soon as you use named argument syntax    for one argument everything that follows    that must also be named    so in this case i can fix this by saying    items to    greet    equals and now i can run this again    and i’ll get the desired three lines of    output once again    now i could mix these up though    and because both of them are using named    argument syntax there are no problems    here and once again we could run this    and we would get our desired output    now we’re going to take a look at how we    can create a simple class in kotlin    now up until this point we’ve been    working within    a single main.kt file    however now that we’re going to move    into classes let’s go ahead and add a    new file    so we’ll come over to our project panel    right click source go to new kotlin file    or class    now we’re going to come down and on this    drop down we’re going to select class    and we’re going to name this class    person    and then hit enter    we can see here then that it    automatically has created a person class    for us    and i might notice that this class is    quite simple    so let’s take a look at how this class    actually works    to start we have the class keyword    followed by the class name    and then really that’s it    we could actually even optionally remove    these curly braces since we’re not    defining any properties or methods at    this time    if we wanted to then    use this class we could return to our    main function here    and then we can create an instance of    the class like this    so we’ll create    a variable    named person    equals    person    now this syntax right here    is how you create a new instance of a    class notice there’s no new keyword in    kotlin you do not have to explicitly    call new you can simply specify the    class name and then the constructor and    any arguments that you need to pass into    it    so you may notice that we were able to    create an instance of the person class    using this empty constructor    however    if we go back to our class definition    we don’t have any constructor defined    this is because    when you’re defining a class in    clockline    if you do not have any    properties defined in your primary    constructor    or any arguments defined in your primary    constructor then you can actually just    omit that primary constructor all    together    so what we see here class person    is really a shorthand form of this    if we wanted to explicitly define    this    primary constructor we could do so by    adding the constructor keyword and then    the open and close parentheses you’ll    see here that it actually gives us a    message recommending that we remove the    empty primary constructor    now we could also    modify this primary constructor by just    removing the constructor keyword and    moving the open and close parentheses    directly after the class name    however we still get that same    recommendation to remove the empty    primary constructor    so now let’s add a primary constructor    once again    and this time let’s actually define    a parameter that must be passed into    this constructor so if we’re creating a    person class    let’s pass in a first and last name    for this person    so    we could say    first name    stream    last name    string    so now we have two unused parameters    that we pass into the constructor    and now if we come back here to the    creation of an instance of our person    class    we’ll see that we now have a compiler    error saying no value passed for our    parameters    so i’ll go ahead and i’ll pass in my    first    and last name here    so now we come back here and we’re not    actually    doing anything yet with these parameters    so let’s change that    let’s define    our first property on our person class    so since we’re passing in first name and    last name let’s define properties for    first name and last name    so we could say    val    first name    stream    val    last name    stream    now you notice that both of these    now have red errors underneath them    saying property must be initialized or    be abstract and there’s a couple    different ways that we can initialize    these    the first way we’ll look at is using an    init block    you can define an init block by using    the init keyword and then open and close    curly braces    an init block is a piece of code that is    run anytime an instance of this class is    run    and you can actually have multiple emit    blocks that will be processed in the    order in which they’re defined within    your class body so within this in-net    block we can initialize our property    values using the parameters from our    primary constructor    so we’ll say first name equals    underscore first name    last name equals underscore    last name    now we have initialized properties    if we look up at where those properties    are declared we see these little    warnings saying can be joined with    assignment what does that mean    well this is the other way in which we    could initialize these values we could    actually get rid of the emit block here    and we could initialize these at the    point where they’re declared by saying    equals underscore first name    equals    underscore last name    so now we’re passing in those parameters    to the constructor and then immediately    declaring and initializing properties on    the class    so now if we go back to our usage of    this person class    after we create the instance of person    we can now access those properties    to access the properties we type person    dot    and then we can access the properties by    their names directly so we could say    last name or    person dot    first name    now you notice that we’re not using a    getter here    in kotlin this is known as property    access syntax    you can reference properties directly by    their name without having to worry about    the getter or the setter    so now if we go back over to our class    we could actually simplify this    even a little bit more    and to do that    we’ll go ahead and remove    these properties    and so now instead of passing in a    parameter to the constructor and then    defining a separate property that    mirrors that parameter we can actually    declare the property directly in the    primary constructor    so to do that we’ll come up here we’ll    remove this underscore since this is now    going to be the property name    and then we’ll add the val keyword    and now we have defined a first name and    last name properties within our primary    constructor directly and if we go back    to our usage we see that nothing has    changed here we can still initialize the    class in the same way and still access    our last name and first name properties    the same way    so far we’ve been working with the    primary constructor within our class    declaration    but it’s also possible to define what    are known as secondary constructors    secondary constructors can provide    alternative means for you to instantiate    an instance of your class    so let’s work with an example    let’s say we want to create a secondary    constructor that takes note parameters    so that we don’t have to always pass    values in when we want to create a new    person object    so to create a secondary constructor    we use the constructor    keyword and then open and close    parentheses    and in this example we’re not going to    pass in any parameters    we then need to call through to the    primary constructor to do that we use    colon    and then the this keyword    open and close parentheses and then now    we need to satisfy any parameters that    are declared in the primary constructor    so in this case let’s define some    default first and last name values    so for our first name we use peter    and last name    we’ll use parker    and then we can define a body for the    secondary constructor    and to just take a look at how this    works with the knit blocks    let’s go ahead and add a print statement    here    that says    secondary    constructor    we’ll then add    an emit block    and we’ll put a message here that says    emit    one    and then just for fun let’s add a second    a net block after the secondary    constructor    and we’ll print out    init 2.    now    let’s run our main function    and just see what happens    so in this case we’re using the primary    constructor    so we can specify in explicit values for    the first and last name    so we’ll see that the secondary    constructor is never called    but both emit blocks are called and    logged out to the console    so now let’s remove the explicit    arguments that are being passed in    and now let’s rerun this    and now this time we’ll see that a knit    block 1 is run and it block 2 is run and    then our secondary constructor was run    so what this shows is that the init    blocks are always going to run before    the secondary constructor now the init    blocks will execute in order in which    they’re defined within the class body    and then the secondary constructor will    be called    now in this example    and actually in many practical examples    when using kotlin on real projects a    secondary constructor isn’t strictly    necessary because of the power of    default parameter values    so in this case we could remove    all of this within our class body    and instead    we could define default values    here in the primary constructor    now if we go back over to our usage    we can still use the person class as if    it had this empty    primary constructor because both    parameters have default values    now let’s look a bit more closely at    class properties    now we’ve already defined two properties    within our primary constructor    both of these are    read only properties so they have no    setter but they do have a getter    available    that getter is how we are able to    leverage property access syntax and    reference those properties directly as    we are doing here in our main function    let’s explore this more fully by adding    another property    let’s add a nickname property in this    case we’ll use var because it’s not    going to be set initially    we’ll call it nickname    string    we’re going to go ahead and make this a    nullable string    and then we’ll go ahead and set that    initially to null    so now    let’s see if we type person dot we see    that we have a nickname property    but unlike last name and first name this    is a mutable property so we can actually    assign a value to this    so we can say equals    and then my nickname growing up was    shades so let’s assign that string to    this nickname property    so if we go back to our person class    let’s look at this property a bit more    closely we’ve already mentioned that    properties in kotlin    will get getters and setters    generated for them automatically by the    compiler    so if your property is a valve it will    have a getter generated if it’s a var it    will have a getter and a setter    generated    but what if you don’t want to rely on    the default behavior of these getters    and setters maybe you want to do some    complex    logic within that or maybe you want to    log something out for debugging purposes    well you can override the behavior of    these default getters and setters and    provide your own implementations    so let’s log out every time a new    nickname is set    to do that    we go to our nickname declaration    and then we’ll go to the next line    and then we’ll    space over four times    and now    if we start typing set we’ll see auto    completion comes up with several options    here    so i’m going to choose this bottom one    so what this essentially does    is allows us to define the function    behavior for when set is called    now when we do this this will generate a    backing field for this property    so to actually assign the new    value to our nickname property we need    to    use a special keyword    called field    equals    value    if we didn’t make this call then the    value of nickname would never actually    be updated    and now    we are free to implement whatever we    want so in this case we could update    this with a log message    that says the new    nickname is    dollar    value    so now if we go back over to our main    let’s see what this looks like so we’re    signing one nickname    person dot nickname now let’s assign    another nickname    in this case we’ll just say    new nickname    now if we run this we can take a look at    the log    so you see here each time we’re    assigning a value to the nickname    property    our log statement is being run    similarly we can override the default    getter    we do this very much the same way we’ll    start by saying get    there’s no new value to set so there’s    no value being passed in so instead    we’ll just log this out say print line    the    returned value is dollar field we still    have that field backing value which is    what is storing the actual value of    nickname    and then we’re going to return    the value of field    so now we’ll come back over to our main    and we’ll use a print statement here    person dot    nickname    and if we run this    we’re seeing that our    setter    is being called multiple times    then our getter is being called and the    value logged out and then finally    our print statement here in the main    function    now that we’ve explored class properties    let’s take a look at how we can add a    method to our person class    to add a method we really just need to    define a function within our class    declaration    let’s create a method called    print    info it’ll take no parameters    and it’s just going to print out the    user’s info    so in this case we use a print statement    and then we’ll use a string template to    print out the first name the nickname    and the last name    so we go back over here to our main    class    let’s go ahead and remove    most of this    now if we want to call a method on our    person variable    we can type person dot    and then print info    so now if we run this    we see peter    null parker    so our method worked however the    formatting is maybe not quite what we    would have want because nickname was    null when print info was called we    printed out the word null    rather than anything possibly more    useful    so let’s refactor this method a little    bit and see if we can improve that    so    let’s create a variable called    nickname    to    print    and then let’s check whether or not this    is null so we say    if    nickname does not equal null    we’ll go ahead and use the nickname    else    we’ll use this more descriptive string    of no    nickname    and now we can update this    implementation instead of using nickname    directly we’ll use this new local    variable    so now if we go over to our main again    and we run this    now we see our output is formatted a    little bit better    now while the output now looks better    this expression right here is a little    bit verbose    this type of check where we’re comparing    whether or not something is null and    then providing one of two values comes    up quite a bit in kotlin    and because of that there’s actually a    convenient syntax we can use that    simplifies this expression so what we    can do is this    nickname    question mark colon    no    nickname    the question mark colon is what’s known    as the elvis operator in kotlin    what this expression is saying    is check what’s on the left side of the    elvis operator    if that side of the expression is not    null then go ahead and return that    otherwise return what is ever on the    right hand side of the expression    so    if we go back to main and run this once    again    we’ll now see that we’re still getting    our updated output    so in this case the elvis operator is    just a much more concise way of doing    that if else check    now i want to take a minute and talk    about visibility modifiers within kotlin    looking at this code here you’ll see    nowhere do we have any type of    visibility modifier specified    however if we go over here to our main    we’re able to create a new instance of    this class we are able    to call the print info method    and we are able to access    all of the properties    this is because in kotlin    classes    properties methods really visibility in    general is public by default    if we wanted to modify the visibility of    any of these we can add one of four    visibility modifiers    so from the class we could add public    here    however because it’s public by default    this is not needed    we could add    internal    internal means that this class is public    within the module so in our case because    we’re in a single module this doesn’t    change anything    we could also make this    private    once we make it private we’ll now see    that it’s no longer available in our    main.kt file    in this case a private class is only    available within the file in which it’s    implemented    now we can apply similar rules to our    nickname property    if we make this    an internal property    nothing changes    and we can still access that    if we make this protected    and go back to our main function we’ll    now see that we’re getting an error    cannot access nickname it is protected    in person    a protected property or method will only    be available within that class or within    any subclasses    and as you might expect if we make this    a private property once again we cannot    access it from our main.kt file    and the same goes for our method    if we make this private or protected    it’s not going to be available within    main.kt    now that we have an understanding of how    classes work in kotlin let’s take a look    at how interfaces work    so we’ll go back to our source directory    go new kotlin violet class    this time in the kind drop down we’ll    select interface    and let’s go ahead and call this    person    info    provider    then we’ll hit okay    so now    the ide has created a person info    provider.kt file    and it’s auto-generated this empty    person info provider interface for us    now like with the class    because the curly braces are empty we    can actually remove those    and this is a completely valid interface    within kotlin it’s empty there’s no    methods that can be implemented and    there are no properties that can be    implemented however this could still be    used as a marker interface for example    in other classes could in fact implement    this interface    in fact why don’t we do that right now    let’s create a    class called basic info provider that    implements person invoke provider    we can actually do that within the same    file we don’t need to have one file per    class or interface within kotlin so to    start we can say    class    basic info    provider    now we want to indicate that this class    is going to implement person invoke    provider to do that    we’ll use a colon    and then we’ll type the name of the    interface    and just like that we’ve now created a    new class basic info provider that    implements person info provider and    because person info provider does not    currently have    any methods or properties basic info    provider has nothing that needs to    implement    now let’s add a method to our person    info provider interface    to do that we’ll come back up to the    interface declaration    we’ll add back our braces    and now we’re going to define    a function signature within this    interface now we don’t have to actually    implement this we just have to define    the name and the parameters that are    required by this method    now once we’ve added this we’ll notice    down below now that our basic info    provider class has a compiler error    saying that it does not implement    the required interfaces    or    add the abstract keyword    so let’s take a look    at how we can address this issue    to do so we’re going to start off by    adding a main function so that we can    play around with this class now one of    the ways that we could solve the compile    issue with basic info provider    is by declaring it as an abstract class    this means it doesn’t need to implement    all the methods available on the    interfaces that it includes but it also    can’t be instantiated so if we try to    come down here and say    val    provider equals    basic info provider    we’ll get    an error saying cannot create an    instance of an abstract class so in this    case we don’t want to make this abstract    because we do want to work with this    class so we can remove the abstract    class keyword    and now we want to actually implement    the required    methods from person info provider    so to do that we can start typing print    info and the ide will recognize that and    if we hit enter it will generate a    stubbed out version of that print info    method    now let’s take a look at how this was    generated    we see that it starts by including the    override keyword    this is different than in java where it    was an override annotation in kotlin if    you remove the override keyword    it’ll actually give you a compile error    in this case saying print info hides    member of super type and needs the    override modifier    so it’s very specific in indicating that    you do need to include that override    and then after that it simply matches    the rest of the method declaration from    the interface    so here we’re now free to define the    behavior of this interface however we    want    you also see down below that now that we    have implemented the interface fully we    can actually create an instance of this    class    so    if we implement this    right for now    just printing out print info    we can come down to our main function    we can type provider dot    and then we can invoke the print info    method    and we’ll pass in    a empty instance of the person class    and we’ll see here that it executes that    print info method    so that’s a very simple example of how    we can define an interface to find a    method on that interface implement it    and then run it on that implementing    class    let’s improve upon the implementation of    print info    so here we’re going to say    basic info    provider    and then below that we’re actually going    to call    the print info method on our person    class    so now if we run this    we’ll see that we have that basic info    provider being printed out    and then the info from the person    now perhaps we want to    encapsulate this logic within the    interface itself maybe this print info    method should always generally work in    the same way    well we could actually move the    implementation    that we’ve just defined    right here up into our interface    see in kotlin interfaces can provide    default implementations    of an interface method so now we can    actually    remove the implementation of print info    from basic info provider    and the code will still compile and run    so now if we run this    we’re going to get the same output    however there’s an issue with this we    see now in our person info provider    interface    we are including the basic info provider    string    well we probably don’t want that since    it is an implementation detail of basic    info provider    so here we could actually leverage    another interesting feature of    interfaces in kotlin we can provide    properties on our interfaces as well as    methods so we’ll define a property    called provider    info    of type    string now you might be tempted to give    this a default value but    if you do you’ll see that we actually    get a compiler error saying property    initializers are not allowed to    interfaces    so you will in fact have to override    this in any implementing class    but now that we have this provider info    string    we could modify our print info default    implementation    to print out that provider info so now    we’ve kind of encapsulated this logic    into the interface itself    and then the basic info provider class    can now just override that provider info    property    and we override a property in much the    same way as a method    so we’ll use    override val provider info of type    stream    and then we have to provide    the getter    so in this case we’ll say    basic    info    provider    and now if we run this once again    now we’ll see that we are picking up the    overridden property value    and then still relying on the default    implementation of print info in person    info provider    and now if we wanted to still override    print info    we could absolutely do that and we could    call through to the super implementation    if we would like    and then we could print out anything    else here    and if we run this one last time    we’ll see that we are now relying on the    property    the default implementation of print info    as well as now our additional logic and    the overridden implementation of print    info    next up let’s look at how we can    implement multiple interfaces with a    single class    to start    we’ll add a new interface called session    info provider    and then we’ll add a method to this    called get session id    and that will return a string    and so now if we come down to basic info    provider we want to make this class    implement session info provider as well    well all we have to do is to add a comma    after    the previous interface declaration    and now add    session info provider as well    and now once we do that we’ll now see    basic info provider telling us that we    don’t implement the required methods    so we can come down here    and implement get session id    and we can return some    session id    now down here on our provider class we    can now see that we can call get session    id on our basic info provider instance    now is a good time to talk about how    type checking and type casting work in    kotlin    to do this we’re going to create    a new function here called    check types    and we’re going to take a parameter of    type person info provider    now let’s say that we want to check    whether this person info provider    is also an instance of a session info    provider    how about we go about doing that    well we could say if    info provider    is    session info provider    and then we’ll print that out    say    is a    session info provider    otherwise    println    not a    session info provider    and now we will call this check types    function and we’ll pass in our provider    variable    so now if we run this    we’ll see    is a session info provider printed out    to the console    so this conditional was able to    determine that the past and info    provider was also an instance of a    session info provider    now if we wanted to flip this logic and    check that it is not a session info    provider    we can add an exclamation point before    that    and then we’ll just flip    these print statements here    and now    once again if we run this    we’ll see is a session info provider    so you have the flexibility there to    check that either way now let’s take a    look at how typecasting works    so within this else block we’ve already    checked that info provider is a session    info provider    so    we could cast it and then call methods    on it as if it was a session info    provider so we could say    info provider    as session info provider    the as is the keyword used to cast    something to another type    dot get session id    so now we’re able to cast info provider    is that session info provider    and call any methods or access any    properties on it that are specific to    session info provider now kotlin also    includes what’s known as smart casting    which means that if the compiler can    check a type and validate that that type    will not change then you don’t need to    do any additional casting    so in this case    we’ve already validated that info    provider is a session info provider    so we don’t actually need to explicitly    recast this we could say infoprovider    dot get session info    and the compiler is performing a smart    cast for us    so here we can access get session id or    other properties and methods on    the session info provider without having    to explicitly cast it each time    we’ve now seen how a class can implement    multiple interfaces as in the example of    our basic info provider    let’s now take a look at how a class    can inherit from another existing class    and override methods and properties on    that base class    to start let’s create a new file    called fancy info provider    within this file we’re going to create a    new class called    fancy    info provider    we then want this class to extend    the basic info provider that we already    defined    so we can do that    by    adding a colon    and then typing the name of the class    that we want to inherit from in this    case basic info provider    now as soon as i do this    you might notice that we have a red    squiggly line here indicating an error    the error says this type is final so it    cannot be inherited from    this is a characteristic of classes in    kotlin    by default in kotlin classes are closed    meaning they cannot be inherited from or    extended    to extend    this basic info provider class    we need to add the    open keyword    by adding the open keyword it now means    that you can inherit from this class so    if we go back to our fancy info provider    you’ll now see that our error has gone    away    and we can now override methods and    properties in this class    now let’s start by overriding the    provider info property    so we’ll add the opening closed curly    braces to our class definition    and then i can start typing provider    info you’ll see that the ide    is suggesting the property available to    us to overwrite so i’ll hit enter and    that will go ahead and auto-complete the    property    now notice it has the override    modifier indicating that this property    is being overridden    and now you’ll notice that it    automatically provides a custom getter    and you’ll see that it defaults    to deferring to the super implementation    of this    so    we could actually    override this just like this    by saying    fancy info    provider    if we were to then come back    to our main function here    and replace this    with an instance of fancy info provider    and we rerun this    we’ll now see    that it is printing out fancy info    provider so that provider info is being    correctly overridden in our new extended    class    now let’s try overwriting the print info    implementation in our fancy info    provider class    so if i start typing    print info once again we’ll see the ide    suggesting the method that can be    overwritten    i’ll hit enter and again by default this    will call through to the super    implementation of print info within    basic info provider    and so i could then add another line    here    that just maybe says something like    fancy info    and if i come    back and run my main function    and now we’ll see the base    implementation the basic info provider    implementation and now this extra line    added by our implementation of fancy    info provider    now i want to illustrate one last point    in regards to inheritance but before we    do    let’s refactor basic invoke provider a    little bit    instead of hard coding the session id    here let’s add a property    to hold that value    so we’ll come here and we’ll    say    val    and we’ll say    session id    prefix let’s say equals    session    and now    we roll    return session id prefix right here in    our implementation of get session id    so now    if i come into    fancy info provider i want to override    that new session info prefix    so to do that i might start typing    session    and you’ll notice that it’s not auto    suggesting that new property that we    just added    this is because to overwrite a property    in    a derived class you have to mark that    property as open this is just like    extending a class    so    we can come here to session id prefix    and add the open modifier    as soon as we do that    if we start typing once again now we’ll    see it’s suggesting the option to    override session id prefix    so just like the provider info property    i can now    override this    and i could say    fancy session    so this is just one other way in which    kotlin works to enforce immutability it    forces you to mark both your classes    your properties and your methods as    being explicitly open for extension    now there’s a small problem with this    new session id prefix that we’ve added    it’s really meant to be an    implementation detail of the class    however    if we come here to our call site where    we’re using a fancy info provider    variable    you might notice    that we can actually access that prefix    directly    this isn’t ideal because like i said    it’s an implementation detail our api    shouldn’t really be exposing that    property now the reason it’s available    is because we have defined it as a    public property    so what can we do about this    well if we want it to be available in    our child classes but not    to the public api    we could add the protected modifier    so now    that that property is protected    down here when we try to access it we    get an error saying cannot access    session id prefix    if we come back to fancy info provider    you’ll see that we can still override    that property without any trouble    now that we’ve explored how we can    extend an existing named class    let’s look at how we can create an    instance of an anonymous inner class    using an object expression    to do that    we’ll come over to our main function    here and now instead of instantiating an    instance of fancy info provider we’re    going to create an anonymous inner class    so    we’ll delete that    and to start off to create our object    expression we can type object    colon and then the name of the class    that we want to extend in this case    it’ll be    person info provider    now within this class body we can    override any    available properties or methods    so in this case i’ll update the provider    info and just say something like    new    info    provider now notice below here    that our provider dot get session id    call is now being marked as an error    that’s because there is no get session    id on person info provider    but we could go ahead and add a new    method to our object expression here so    we can just say fun    get    session i    id    equals and then we’ll just put in a    value here    so you see you can not only override the    existing properties and methods but you    can add to them as well just like you    could in any other named class    and now if we    run this code we’ll see new info    provider being printed out to the screen    so an object expression allows you to    create an anonymous inner class so you    don’t have to create a new named class    so this might be useful for things like    a click listener if you were working in    let’s say android development    now that we’ve explored object    expressions we’re going to now look at    companion objects and to do that we’re    going to create a new file    we’re going to name that file entity    factory    now imagine we want to create a factory    to create instances of something called    entity so to start we might create an    entity class    and maybe that class will have    a single    id    property to start    now we want to make this a factory like    we said so what we might want to do    is change this constructor    to be private and so now if we add a    main function and we try to create an    instance of entity    we’ll see that we have an issue here    we’ll notice that there is this error    saying cannot access init it is private    to entity so this is because of that    private constructor    well so what can we do    this is where    a companion object could come in handy a    companion object is an object scoped to    an instance of another class    so within our block body here    we can type companion object    now we can    create a    create function    called fun    create    and we’ll have that simply return an    instance of entity and for now we’ll    just pass in a placeholder id    so now we can come back down to our main    function    and we can type entity    dot    companion dot create and we can use this    to create an instance of that class    this works because companion objects    have access to private properties and    methods of that enclosing class    now in this case we can actually    shorten this    by removing the reference to companion    altogether the name companion is    implicit and if you’re using it from    kotlin you can leave it off however if    you were using this companion object    from java you would have to reference    that companion object instance directly    you can also rename your companion    object so if we wanted to    name this something like factory to be a    bit more explicit    we could then say dot    factory    and reference it that way and so again    not needed from kotlin but it could be a    good way to make your code more    understandable from the java side of    things if you’re doing a lot of java to    kotlin interop    we can also store properties within our    companion objects as well so in this    case we could create a const thou    id    equals id    and then we could come down here and    replace our entity and pass that in    now that we have this id property added    to our companion object we can reference    it from other calling code as if it was    a static property like we’re familiar    with from java so we could do that by    typing entity dot    and then we can reference that id    property directly    now companion objects are like any other    class and that they can also implement    other interfaces    to demonstrate that we’ll create a new    interface    called id provider    with a single method    just called get id    that will    return a string    now we can come down to our companion    object declaration    and we can    make it implement id provider the same    way we would with any other class    we can then choose to implement the    required members    and then here we will just return a    simple id    and so now    when we create our instance of id we    could rely on this getid method if we    wanted    so you see companion objects can be    quite flexible if you need them to you    could use those to compose other types    of behavior    store your semi-static properties or    methods    and use them to create factories by    referencing private inner properties or    methods of the enclosing class this is    really what you would want to leverage    if you want functionality similar to    that of static classes members and    fields from the world of java    now that we’ve covered object    expressions and companion objects let’s    take a look at creating an object    declaration    to start we’re going to clean up some of    this code we’ve been working with so we    will remove this implementation of    id provider    and we will    go back to using a placeholder id    we’ll remove this reference to entity id    and we can remove this id provider    interface    now what are object declarations an    object declaration is a convenient way    of creating    thread safe singletons within kotlin we    can do this by using the object keyword    and then    a class name in this case entity factory    now within this you can add any types of    properties or methods that you would    like so let’s start    by migrating    our    create method from our companion object    into our entity factory    and now we can remove that companion    object    and instead    we can reference entity factory    dot create    now there’s one small problem with this    so far which is that entity still has    only a private constructor now we’re    going to    remove that private modifier for now so    that we can use that constructor however    very shortly we will continue to    refactor this code to limit the ways in    which entities can be created    now before we go on and continue to    explore some of these other class types    in kotlin    let’s add to our entity class by    implementing tostring so that if we    print out an instance of entity we get    some nice user readable text    so we can start typing tostring    and then i’ll use a    string template here    and we’ll say    id colon    is id    and then we will also    add in a    name property here val    name    of type string    and then we’ll say name    and then substitute in that name    property and then here in our create    method    we will just put in a generic name    and now down here    we can use    a print line statement    and pass in our instance of    entity and now we see our    new tostring text being printed out to    the console so this will help us going    forward demonstrate some of how these    other classes are going to work    all right now that we can print out    useful information about an instance of    an entity    let’s refactor our create factory method    to actually differentiate instances of    entity    so to do this we’re going to change this    and make it no longer a single    expression function so we will add    the return type of entity    and then we’ll add a return keyword and    now we’ll add entity    now the first thing we want to do here    is actually add a proper id value    so here we could say    val id equals you do id    dot    random uuid dot 2    string    so this will give us a new random    identifier    and then we can pass that into our    entity    but now we have this name property so    what can we do to pass in a name here    well one thing we might do is think    about differentiating between different    types of entities so in a very basic    case maybe you want to differentiate    between easy medium and hard    difficulties of these entity types so we    might want to then have some way of    passing or indicating to this factory    method what those different types should    be    so one way we could do this is with an    enum class    now if you’re familiar with java an enum    class is going to be very similar to    what you’re familiar with from enums in    java    to do that we can start typing enum and    then class    and then in this case we might name this    something like entity    type    then open and close curly braces and    then we can iterate the different    instances of the enum so in this case we    might say easy    medium heart    so now we can come down here to our    create method    and then we can add a type parameter    of    entity type    and so now we could say val    name equals    when    type    and then we’re going to    add in the remaining branches so now we    have a branch for each    of our entity types    and then for a basic name i’m just going    to map these to a string    so say easy    medium    and heart    and so now i can pass in that name    so now our factory method actually    allows us to differentiate and create    different types of instances    so    down here we might start off by creating    an easy entity    and then we’ll print that out and we    might say val    medium entity equals entity factory dot    create    entity type medium    and then we can    print that out    as well    and if we run this    we’ll now see that we have a unique    identifier for each entity    and then we have the customized name    based on that entity type so the    addition of this enum class to represent    our entity type has allowed us to pass    in different types to our factory method    and then customize the way that those    entities are created by mapping the    entity type to a name    now in this case we’re mapping the name    very closely to the name of the actual    class itself    so to make this a little bit easier and    more encapsulated there’s a couple of    things we could do    so the first thing we could do    is take advantage of the name property    on an enum class    so to do that we could reference our    type dot    name    so this is referencing the name of that    actual enum class    and if we run this we can see what that    name looks like    so you see it’s easy all in capital    letters this matches exactly    the way that the class name is actually    defined    so this allows us to    reference the classes name directly    without having to map it manually now    this is nice however we don’t have a lot    of control over the formatting here    so another thing we could do is actually    add a new method to our enum class    so in this case we can add fun    get    formatted name    and then we can reference that name    property    dot    to    [Music]    lowercase    dot    capitalize so this will return us that    pre-formatted name and capitalize the    first letter    so now down here we can update our    medium mapping    and type    type dot get formatted name    and so now if we run this code again    we’ll see that the first one by using    the name property directly is all    capitalized but now by using our new    formatted method we have a nicer    formatting similar to what we were using    before    so it’s just one example of how you can    define an enum class and then add    additional properties and methods that    class like you would any other class    now let’s continue refactoring this code    to further differentiate between    different types of entities    to do that we’re going to leverage a    sealed class    sealed classes allow us to define    restricted class hierarchies what this    means is that we could define a set    number of classes all extending a base    type but those classes will be the only    ones that can extend that base type    so one example of this could be a    loading state or result state for a    network operation it’s either going to    succeed or fail and there aren’t really    any other options    so in our place we’re going to create a    sealed class with an easy medium hard    and help entity types to start creating    our sealed class hierarchy    we’re first going to remove    the properties from our entity class    as well as this existing    override of the tostring method    the next step is to add the sealed    keyword before the class keyword in the    entity class declaration    as soon as we do that    we’ll start getting an error above where    we try to create an instance of entity    this is because you can’t instantiate    based sealed class types directly    so this is now where we will create each    type within our sealed class hierarchy    so the first type we’re going to create    is    a data class to represent easy entities    and then we will add the properties we    want in this case the id and name    and then we want to make sure that we    inherit from entity    so next up we can copy that    and update the name    for the medium type    and now for the third type once again    we’ll copy that we’ll name this hard    but now we’re going to add an additional    property this property will be called    multiplier and will be a float and this    could represent some type of difficulty    multiplier if we were creating a game    for example    now notice that all of these types    within the sealed class    all extend from entity but have    different types of properties    this is one of the key differentiators    between sealed classes and enum classes    with sealed classes you can have    different properties and methods on each    of these type and the compiler can    perform smart casting to allow you to    use these different properties and    methods as you would like we can also    use different types of classes itself    within our skilled class so you notice    that these are all    created as data classes however if we    wanted to remove data from one of these    that would be perfectly fine    we could also use    object declarations within our sealed    class hierarchy so this case we’ll    create an object class called help to    represent some type of generic static    help entity within our program    now because help doesn’t have a    constructor because it’s static    in this case we can add a class body and    we could add a    name    and add help directly and in this case    we won’t add id since it’s a singleton    and there’s only going to ever be one    instance anyways    now that we have our sealed classes    defined we’re going to update our    factory method to instantiate and return    different types of entity    classes so we’ll come up here to our    return statement    and instead of returning an entity    directly we’re going to use a win    expression    based on the    entity type enum class    we’ll then add all of the needed    branches    and so when we have an easy type we want    to instantiate an instance of the easy    class    so to do that we’ll type easy    and then we will pass an id and name    and similarly for medium    type entity.medium    id combat name    and now for hard once again    we’ll pass in entity dot hard    id    name    but now again we have this additional    property type and the compiler    recognizes that so for now    we’ll just pass in 2f as our multiplier    now notice though that we have this help    entity being unused so let’s update the    factory to allow us to create instances    of the help type    so we’ll come up to our entity type enum    class    and add a    help type here    now notice as soon as we added that    additional type on the entity type enum    class    our when expressions    warned to us that we need to add an    additional branch    so to do that i’ll add    the remaining branch here    and i’ll default to type dot get    formatted name    and once again below here i’ll add the    remaining branch and in this case    i’m just going to return help directly    you’ll notice here that help is giving    us an error it’s saying required entity    found entity dot help    this was done to demonstrate what    happens if you do not extend from the    base entity type so if we come down to    our entity class here    and notice our object exploration for    help    if we then add    a colon entity to extend from entity    we’ll now see that error go away    so this is a good example of how the    compiler can help give us this nice    static type checking and all of these    things and if we are combining    enum classes with sealed classes with    these web expressions    it allows us to    be sure that if we add a new type or a    new branch somewhere that we have to    handle that effectively because the    compiler will warn us or even give    errors if we’re not handling all of    those different branches    now let’s come down to our main function    and demonstrate one of the advantages of    representing our entities as a sealed    class hierarchy    so if i remove    everything but this first    instance of creating an entity    i’m going to specifically add    a type here of entity    and so now if we come down again we can    use a when expression    and we’ll say    [Music]    now we can come down here    and    use a one expression to do some type    checking about the entity that we have    just instantiated    so here i’ll say val    message equals when    entity    and now again    we’re going to rely on the ide to add    all the remaining branches    so there’s a few things of interest to    note here    so see that for easy medium and hard    it’s adding this is check    so this is going to basically tell if    it’s an instance of that class or not    but then notice for the help    class because that’s an object    declaration    and as a singleton there’s no need to    have is so in that case we can reference    that class directly    and so now here we could add whatever    message we wanted so we could say    help class    easy class    medium class    and    hard class    and then if we simply print that message    out    and run the code    we can see in this case    we’re getting an easy class    and then if we change what we pass into    our factory method and rerun this    we’ll now see that we’re getting the    help class    so now we have static type checking both    and specifying what type of entity we    want back and in checking the type that    we’re actually getting back from that    and so we could use this to then    call any methods or properties that are    specific to that class    and if we were operating on these types    as in a one expression here if we ever    added a new type the compiler would be    sure to make sure that we handle the    addition of that new type    so now let’s return    to our sealed class hierarchy for a    second and dive more deeply into what    data classes are    so you see here both easy and medium and    hard are all defined as data classes    data classes are kotlin’s way of    providing very concise immutable data    types    by defining a class as a data class    it means that it is going to generate    methods such as equals hashcode into    string automatically for you    what this allows us to do is perform    equality comparisons on instances of    these data classes    and treat them as equal if the data they    contain is equal so as an example let’s    explore what this looks like so we say    val    entity 1    equals    entity factory dot create    and we’ll create an easy entity    and then we’re going to create    another version of this    and then now we can check their equality    comparison so we could say if    end to t1 equals    end to g2    println    they are    equal    pedalin    they are    not    equal    so now if we run this what will we see    they are not equal    and that’s to the expected that’s    because if we come back up to our    factory we’ll notice that we’re creating    different unique ids each time so even    though the name is the same the unique    id is different    so now let’s update this    and see what it looks like if we pass    the same data in so in this case we    could create an easy directly    in this case we’ll pass in id comma    name    and then we will duplicate this for    entity    two    and so now if we run this we’re going to    expect to see they are equal    and of course they are    so this is really convenient this allows    us to represent data within our    applications    and compare this data no matter where it    comes from and as long as those    properties are all the same    we’re going to be able to    evaluate these as true now another    really interesting thing that    data classes give us are effective copy    constructors so we could create an    instance of entity two by copying entity    one    so you can see entity one dot copy    and because this is a direct copy if we    run this once again we’re going to see    they are equal    however we could also use named    arguments with the copy constructor to    change the value so let’s say we only    wanted to change the name we could say    name    equals    new name    and once again if we rerun this    we’re going to see they are not equal    so you can see changing a single    property in the data class is going to    impact whether or not two instances    evaluate to true or not when compared    now one thing to notice is this is    comparing    the value of the data themselves    if we wanted to use referential    comparison    we could add a third equal sign here and    this will check whether or not it’s the    exact same reference or not so in this    case they are not equal    however this isn’t all that surprising    since the data was also equal    so what about if we revert this and make    this an exact copy again    so before if we were just using two    equal sign the data would be the same so    it would print they are equal    however by using three equal signs and    using referential equality we see they    are not equal that’s because it’s not    the same exact reference of the object    if we updated this to be entity one    equal equal equals entity one and run    this    now we’ll see they are    equal so that’s just one way in which we    can    check whether or not we have the exact    same object or if it’s two different    objects that have the same data    now also keep in mind    that these equality comparisons are    working off of the generated    equals and hashcode methods generated by    the compiler when indicating a data    class    however    we could update this to change how    the equals or hash code is evaluated and    to do that we would do it like any other    class we could add a class body    and then we could    simply override equals    and or    hash code    now as in java best practice if you’re    going to override one of these you    should really override both of them and    you have to follow the same rules    but you have that freedom if you would    like to    another really useful feature in kotlin    is the ability to define extension    functions or extension properties on an    existing class    this is particularly powerful if you’re    working with classes that you don’t    control but would like to    modify the way in which they are used    you could define your own properties and    methods and define kind of a new api    around the existing class    so an example of this would be adding a    new method to the medium class without    actually defining that method within the    definition of the medium class    so to do that let’s come down here    and you can start off by typing the fun    keyword    and then instead of directly typing the    method name    we can reference the    class name    dot    in this case we’ll type    print    info    and then we can define our function body    so in this case we’ll just say    medium class    with the id    and that’ll be it    and so if we wanted to come down here    and now create    an instance of entity    dot    medium directly    we could do that    and then we could    call that print info method    and if we run that code    we’ll see a medium class and then that    id printed out    so this is great if we know that we have    that exact type that we’re working with    and in cases where we don’t know if we    have that direct type we could rely on    smart casting    so if we update this to use our factory    say entity factory create    entity type medium    now we can say    if    entity two    is    medium entity    now we can reference that new print info    method    this is done because    the    if statement will only evaluate to true    if that cast is successful so anywhere    within that context    it will automatically perform the smart    cast for us    and like i said before not only can we    define extension methods but we can also    define    extension properties as well    to do that    we could start off by saying vowel or    var in this case we’ll say    vowel    and then again we’ll reference the class    type so    medium    dot    we’ll say info will be this property    name    string    equals some info if you do that notice    that we have this error    if you look it says extension property    cannot be initialized because it has no    backing field so to actually create an    extension property for an existing class    you need to rely on backing fields    thankfully the ide can generate this for    us convert extension property    initializer to a getter    so once we do that you’ll notice here    that we have still defined our property    but now we’re relying on this custom    getter for that property and so now if    we come back down here within our if    statement that’s doing our smart cast    for us    we could reference that new    info property directly    so    this is how extension functions and    properties work you could use these    anytime you want to add additional    functionality to an existing class    you might notice within the kotlin    standard library that many functions and    operations work by using extension    functions and classes they are    particularly effective when using them    with templated types because it allows    you to define the same common    functionality across any type that    matches that template    now up until this point we’ve covered a    lot of things we’ve looked at the basic    type system of kotlin how to work with    different variable types how to work    with basic functions and then diving    into more advanced functional topics    like named arguments and default    parameter values and then we took a deep    dive into modeling data with kotlin so    now we’re going to circle back to    functions and specifically take a look    at higher order functions and how to    work with functional data types    now what are higher order functions    higher order functions are at functions    that either return another function or    that take functions as parameter values    now much of kotlin’s standard library is    built on top of higher order functions    and it’s what really allows us to write    highly functional code by leveraging    that standard library    so let’s take a look at how we can write    our own higher order function    to start we have a new kotlin file    and we’re going to define a new function    so we’ll call this fun    and then we’re going to call this    print    filtered strings    and now the first argument to this is    going to be a list of strings    so we’ll call this list    and then define it as list of string    and now the next thing we’re going to do    is define a parameter which will in fact    be a function    that function    will take in a string and return a    boolean we can then use that to filter    out values in the past collection    so to define a function parameter you    could start off by defining the    parameter name as usual    in this case we’ll name it    predicate    followed by a colon    and now you have to define the type as    you normally would to define a    functional type you can start by adding    your parentheses this will define the    parameters of the function being passed    in to    your other function    so in this case we are going to take a    string    you’ll then add    the arrow    and then you want to define the return    type so in this case    that will be boolean and now we’ll add    the open and close curly braces to    define our block body so now we have a    parameter called predicate which will be    a function that takes in a string    parameter and returns a boolean    now we can implement our print filtered    strings function    to make use of that predicate function    to filter out any strings in that past    list so to implement this function first    off we want to iterate over each string    in the past list    so to do that we could say list dot    for each    and now we will be able to iterate over    each of those strings    so now what we want to do is evaluate    the predicate for each string in the    collection so we can call the predicate    function in several different ways    so to start we’ll say if    and then the easiest way to invoke the    predicate    is to simply say predicate    open and close parentheses    and pass in the parameter value a    parameter that is a functional type can    be called    as if it was a regular function as long    as you can satisfy the required    arguments    so in this case we can say if predicate    returns true    then we can print out that string now to    test this we’ll come down here    and we will add a main function and we    will say val list equals list of and    then we could say something like    kotlin    java    c plus plus    [Music]    javascript    and now we could call print    filtered strings    pass in our list    and now we need to pass in a function as    the second parameter to print filtered    strings so we can do that    by specifying a lambda    and in this case    we will say    it dot    starts with    k    so this lambda is going to evaluate to    true if any of the past strings begins    with a k now if we run this function    we’ll see only kotlin printed out to the    screen    if we were to update this to print    things out that started with a j    we’ll now see javascript and java    now one thing to notice is that in our    invocation of print filtered strings    we’ve passed our lambda within the    parentheses of that function invocation    however this is something that we don’t    have to do    as we mentioned earlier we can take use    of land the syntax which says that if    the last parameter of a function is a    function    you can specify that as a lambda outside    the function body    so we can restructure our function to    look like this we can pass in the list    first and then specify our lambda    outside of the parentheses so this is    actually very similar looking to the for    each function which we called up above    and in fact    if you look at the implementation of    four each it is in fact a higher order    function    the lambda that we specify after    invoking for each    is a function which will operate over    each string in that list now if we come    back up here to our implementation    notice that we    are calling the    function parameter directly as if it was    a regular function    so this works absolutely great in most    situations however    if we were to make this function type    a    nullable type    by wrapping in parentheses and adding a    question mark    we’ll now see an error in our    implementation of print filtered strings    that error basically says that you    cannot invoke that function parameter by    using the parentheses directly if it’s a    nullable type    to get around this    we can make use of the invoke method on    that functional type    and then we can make use of the    safe call operator    and now by updating this to do a safe    invoke call on the predicate function    we can handle this whether or not the    predicate is null calling invoke will    invoke the function just as it would any    other invocation of a function    so now down here nothing has changed in    how we can call print filtered strings    however    we could also    pass in list and now we could pass in    null as a null function so we’ve seen    how we can treat functions as parameters    to other functions    and these function parameters are really    treated as types just the same as let’s    say integer or string kotlin has this    idea of functional types it’s a first    class part of the language this means    that we could define a variable of a    functional type and then pass that    variable in any time we needed a    function parameter that matched that    function signature    so an example of this    might be something like    val    predicate    and then we will define our function    type to match that of our print filtered    strings function so in this case it’ll    take a string    and    return boolean    and now we’ll define our function    the same way that we were doing it    before by saying if the string starts    with a j go ahead and return true now    instead of invoking print filters    strings with a lambda passed to it    we can pass in    our predicate variable directly and now    if we run this we’ll see the same output    as we would before    so this allows us to store function as    variables    this could be really useful for things    like optional    input handling for example maybe you    have a view on some screen and you want    to be able to specify a click listener    for that view you could define that as a    lambda property on some class and allow    client code to set that click listener    as needed as we mentioned before higher    order functions include functions which    take other functions as parameters    as well as functions that return other    functions so let’s define a function    called    get    print    predicate    and it’ll take no parameters    but we can define its return type as a    function which takes a string    and returns    a boolean    and now we could return that value by    saying return    and then we can pass a lambda    and say it dot    starts with j    so we’re passing essentially the same    type of lambda that we’ve been using in    these other examples but now we’ve    wrapped it in this other function    and so now instead of passing predicate    directly    or instead of    defining a new lambda as our function    parameter    we could instead call get print    predicate as a function on its own which    will then return a function which then    can be used as    the predicate for print filtered strings    and if we run this once again    we’ll see that our output hasn’t changed    at all    so higher order functions can work as    both    inputs and outputs and kotlin allows you    to define properties with functional    types    so through this functions really become    a very powerful and first class part of    the language that can start to replace a    lot of other instances for example you    might find yourself relying more heavily    on functions to define things like event    or click listeners rather than defining    concrete interfaces    for those same types of functionality    now as was recently mentioned much of    the kotlin standard library is built    around higher order functions and    especially higher order functions    defined    with generic types    so if we look at the implementation of    for each    well notice that this is actually an    extension function    as well as a higher order function    so for each works on generic iterable    type and takes in a function parameter    that takes in that generic type and    returns unit    so this essentially allows us to iterate    over each element    in the collection    and then call that action on it and it    doesn’t have to return anything    and similarly for each index    takes in a single function parameter as    well but this one takes in an int to    represent the index as well as the    generic type this allows us to iterate    over each element in the collection    while incrementing a counter and then    passing that counter into the function    parameter    as the index    the power of generic types extension    functions and higher order functions    allows us to write single    implementations of these methods and    then reuse them over any type that we    can think of now this is very powerful    and can allow us to write much more    functional code without having to    redefine these methods and functions    for all of our different types    so let’s take a look at example of how    we can combine some of these different    functional operators to perform complex    operations with very little code we’ll    come into this new main function here    and we’ll start off by defining a list    of strings once again    now let’s look at some ways in which we    can chain these functional operators    together    to do more interesting things    so as we’ve seen before we could do a    simple    for each to iterate over    each item in this collection    and print it out    and if we run it we’ll notice that we    see all of the programming language    printed out to the console    now what if we wanted to print out    only the strings that start with j    well similar to the functions we were    working with before    we could do that by making use of a    filter operation    so    we have a lot of options to choose from    in this case we will    just choose a generic filter and then we    will use a predicate which says    it dot    starts with j and now if we run this    we’ll see we have only java and    javascript printed out now what if    our collection    included some null values    so as soon as we add null    we see now here in our filter operation    it’s warning us that hey this value    might be null you need to add a safe    call    well in kotlin oftentimes we don’t want    to work with null we want to try and    hide null as much as possible    and so we could make use of another    functional operator    called    filter    not null    what this does is immediately filter out    any null values up front so everything    past that in the functional chain will    be guaranteed to be not null so as soon    as we added filter not null we no longer    had to deal with a possible null string    and if we run this once again    we’ll see only java and javascript    printed out    now what if we wanted to change the type    of this let’s say we wanted to convert    this from a string to an integer which    represents the length of that input    string    we could do this type of transformation    using a map function    the map function will take in whatever    the previous type is in this case string    but it’ll allow us to return any other    type we want so in this case we might    define our map function as simply    returning the length of the string    as soon as we’ve done that now below    that in the four each the type has    changed from string to end    and now if we print this out    we’ll see four and ten printed out    four representing the four characters in    java    and 10 representing the 10 characters in    javascript    now let’s remove this    mapping    and let’s remove the filter    and instead let’s imagine that    we want to take only a certain number of    items from this collection    so we could do that    by using the take function and passing    in let’s say three    what that’ll do    is we’ll take the first three items from    that collection and then we’ll be    printing out each of those three names    so you see in this case we’re getting    kotlin java and c plus    alternatively if we didn’t want to take    the first three elements in the    collection we could use    take last to take the last three    so in this case we see java sees plus    plus and javascript and it has skipped    over kotlin since that was not one of    the last three elements    we can also do other transformations    such as associating the input values    with some other value to return a map    so let’s create a map    that essentially maps the string    to the number of characters in that    string    so to do that    we could say    associate    and then in this case we could say it    to it    dot length    and so now in our for each function    instead of iterating over strings we’re    iterating over    map entries of string and end    so    in this case we could now    use a templated string    and say    it dot value    comma    it    dot key    and if we print this out    we’ll see the length comma followed by    the name this makes it really easy to    map all of the input strings to some    other value and then iterate over that    map    now what if we didn’t want to iterate    over the map but instead just wanted to    hold on to that in a variable    well instead of using it for each at the    end    we could    assign this to a variable just like this    the kotlin standard library also    provides    a variety of functions to help us pull    out individual elements from a    collection    to demonstrate that let’s create a    variable    called    language    and then we’re going to perform    different operations on our list to grab    a single language string from our list    so we could do that in a number of ways    we could say list    dot first    and if we    print this out    we’ll expect to see kotlin as that is    the first language in the list    alternatively    we could say list.last    and in this case you’ll see that it’s    actually printing out no since a null    was the last value in that list    now if we didn’t want to retrieve    a null value from our list and instead    wanted the last non-null value    once again we could add the    filter not null function which we used    previously    and now    if we rerun this    we’ll see javascript printed out instead    since this is the last non-null value    now what if we wanted to find a specific    item in the list    let’s say we wanted    to use the find function    and in our predicate we’ll say it dot    starts with and we’ll pass in java as a    string so this is going to find the    first value in this list    that starts with java so in this case    it actually returns us java    and alternatively we could use    find last    to find the last element in the    collection that matches this predicate    in which case it’s going to return    javascript    now what happens if we are searching for    a string which doesn’t match our    predicate    we can test that    by looking for a string which starts    with foo    if we then run this    we’ll see null printed out to the    console this is because    there is no matching string so find last    is going to return no and then the print    line statement will print out null if it    has a null value    well what if we didn’t want to work with    null what if instead we wanted to use an    empty string as the placeholder    well strings    in kotlin have a useful function called    or empty so we can actually chain that    directly off of find last here    and call or empty    so what this will do is return either a    non-null string or    a static empty string    so now if we run this once again    instead of null we’re just saying empty    we’re not printing anything out so this    is one way in which you could default    your collections or your strings to an    empty value as opposed to a null value    this is something you might want to    consider doing more and more of in    kotlin as you start to move away from    relying on null    so as we’ve seen    kotlin has first class support for    functions including functional types and    higher order functions    and the kotlin standard library builds    upon those tools and provides a rich set    of functional operators for us to use    this allows us to build powerful    functional chains to transform our data    and make complex workflows much simpler    all right that’s it for this tutorial    you now have a good understanding of the    fundamentals of kotlin and how to work    with it and you’re now ready to start    taking that knowledge and applying it to    other domains until next time devs    you    


Leave a Reply

Your email address will not be published. Required fields are marked *