Kotlin 102 - Beyond the Basics • Hadi Hariri • GOTO 2018

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Im a simple man, I see Hadi Hariri I upvote

👍︎︎ 26 👤︎︎ u/llusx 📅︎︎ Feb 02 2019 🗫︎ replies

Two people I like to listen to one is hadi and the second is Jake, they both explain anything in a format that your brain can consume easily.

👍︎︎ 16 👤︎︎ u/socialflasher 📅︎︎ Feb 02 2019 🗫︎ replies
Captions
[Music] okay so I'm going to start with a few different things show you some things around column which you don't get in an introduction course although Kotlin and such isn't such a complex language so really it's it's easy to essentially pick up but let's dive in a little bit so higher-order function which you're all familiar with so I have like a function that takes an int eternity another integer and returns an integer and that's a higher-order function right so it's a function that takes a function or a function that returns a function and in Kotlin we can you know have multiple functions so I can have for instance a GE over here that takes no parameters and returns nothing wealth returns the unit which is actually different to nothing right it truly is unit is not nothing unit is an object which is different to a class so how many of you are JavaScript developers here it's and not to embarrass to put up their hands so object is the equivalent of object in in JavaScript you know how you went from Java or C sharp to JavaScript and you like oh I'm gonna take everything I brought with me so let me in create this amazing system in JavaScript called classes and hierarchies and everyone's like no don't do that you have objects in calling we have objects and we have classes object is essentially a singleton this is how you implement a singleton in Kotlin you just write object that's it you don't have to buy a book which was a good book by the way although now nowadays you can't say you've read the Gang of Four they'll frown on you they're like oh you're not doing functional programming then so and I was saying that it's not nothing right because nothing is something in Collier how many of you have heard of nothing okay so nothing is something so this is do something that does nothing and if I have unit and I do throw exception this does nothing right because if I write it does nothing well it throws an exception but if I come to my main function here and I say print nine hello that will work if I write throw exception law that won't and if I well that will throw an exception and a five right by the compiler will say that this doesn't work because it's never going to reach that code because exception being thrown so but if I write here do something it's going to not work as well because it's of the exception however if I remove this and I take this line over here and I move it down print line is still going to supposedly work right because it's saying well it's it's going to work it's gonna call a method it's going to come back and that's the difference between unit and nothing because nothing actually says that this function is not going to return it's going to essentially be nothing and there now it says that this code is unreachable so there is a difference between unit and nothing and as as I always say nothing is nothing for you to worry about so let's move on so we have this do something and we have this higher-order function and one of the things that we have in Kotlin if you're familiar with obviously you've got the string extension you've got the function extensions but you also have property extensions right so very good example of this is always like I can have a long that I can write or a float that I can write using literal so I can write ten F that means that it's an actual float and we we worked with big decimals which we loved to work with I want to be able to write big decimals these ten BD I cannot do that because there's no such literal for big decimals I could do the next best thing to that which is creates an extension property right so well I could create an extension function write that but it doesn't look that good but I can create an extension property so I can create an extension to integer for instance that returns a big decimal and then this is going to return a big decimal of this right so that is giving me an extension property okay so one of the benefits of this is that apart from making it very nice to read look at is that you can essentially delegate them the the functionality of a property to something else right to external function which you can reuse over and over again and that's one of the benefits of delegated properties right so I have a class with a bunch of delegated properties and I can delegate these to other functionalities and then share them across multiple classes and that's where we have for instance a bunch of built-in delegates so you all probably familiar with the lazy delegate right how many of you here familiar with lazy so lazy essentially is lazy initialization of a property it's going to initialize it when it's accessed for the first time and it's just gonna initialize that code and it's not going to run that code ever again and that is done by using declaring the property lazy and then using by and then lazy which is the built-in delegate and then I pass in the actual function that is going to initialize our property so if we go over to lazy over here we can see this that this is a higher-order function that takes an initializer it also has a overloaded versions which allow you to pass in the different type of initialization that you want to do synchronization on shared properties but that's one of the most common ones but there's a few other ones that are also built into the standard library right one of them is the veto book so veto wall is a delegated property which allows you to say if a certain condition is matched then update the property if not do not do it right without you having to write that logic over and over again so in this case I'm saying that I've got the property I've got an old value I've got a new value and I say that if the new value starts with an S then update the value if not then don't update the value so here where we're creating for instance a class veto and then I say set the value I said it to change I print out the value I set it to strange I print out the value in principle the value should only change after I hit strange right so if we run this you can see that on the first call it's not actually setting the property okay and it's setting the property on the second call over here when I hit strange so this veto ball lazy and observable are some of the built-in delegates that we have in in the standard library which you can use but of course you can also create your own property delegation in common and essentially what you have to do is you have to create a class that defines two operators one of them is called get value the other one is called set value and much like you saw in the veto of all example what I'm getting here is some information about the actual class then I'm getting information about the property K property what is K property that's just like property but prefixed with a K that's here and that's one way to explain Cortland take everything Java and prefix it with a K and then release libraries with a K intercalated with a C know that one with a K and that's called it so K property is a Kotlin property so it's essentially reflection enhanced right so in Kotlin you might be aware that you can use Java reflection you can also use Kotlin reflection it's like Java reflection but better it's got some additional things that has intrinsic entrance intrinsic knowledge of Kotlin such as properties so this is how you can create your custom delegates and then essentially just use these delegates anywhere you want in your own classes properties top-level variables etc okay so one other thing that we have in collin is algebraic data types or we have we represent our to break data types with sill right so here is a simple example of what would be an algebraic data type which if you're not familiar with that concept now generic data byte data type is a type that can be a one type or another for instance boolean boolean can be of type true of type false so in calling you can essentially do the same thing by declaring this as an open result right so here now what I'm saying is that my class can inherit from result and I have two cases this is very common for instance if you want to move away from exceptions or you want to have a function that returns one of two different types in case of success or failure you could do something like this right and if you do this this is absolutely valid the problem with this is that if I come here and let's all go over for example to a file and I say class sometimes and sometimes inherits from result right that is going to work as well right because result is an open class so if I'm writing code that is checking for that that kind of sucks what you can do instead is mark class as sealed instead of open and sealed essentially what it means is that it's closing off the hierarchy okay so now you cannot inherit from that class beyond what you've all inherited and you might be asking what is that well whatever is on that file so sealed will close the hierarchy off to that file right so over here sometimes no longer works but over here sometimes does work and this doesn't necessarily need to be but up top level classes you can also have it as nested classes do you have a question or did I answer it oh I'm too loud that's what my family always says to me I'm sorry I'll try and talk a little bit better that's better so you're sitting there like this suffering with pain I'm so sorry so I have I I have tinnitus now you know how I feel except it's not my own voice it's some damn ringing anyway so I'm also happy to know that my explanations are so awesome that you only care about the volume that's like recently I was giving I was giving a webinar for for one hour right one hour webinar and I had of all people one of my heroes Eric Meyer as a moderator right so 50 minutes in nobody's asking questions and eventually Eric says how do we have a question I'm like yes what is it it's on Collin right that the boy Evan are there like yes someone's asking what is that arrow in IntelliJ IDEA anyway when I grow up I'm gonna be a programmer numbers 1 to 100 now you all know that in Collin if I write something like this and then I do for instance numbers filter it is less than 10 or let's say it is divisor by 5 if I could type and then say take 30 what's going to happen here is what this is eager evaluation right so essentially it's going to look through the entire list and then it's going to filter out those that are dividable by 5 even though at the end of the day all I want is the first 30 of them if you want to have lazy evaluation that is possible in Colleen all you need to do is take any iterable and call as sequence on it as soon as you call as sequence that now becomes lazy evaluated right so essentially the same as Haskell where everything is by default lazy evaluated so this works with essentially anything that is an iterable if you actually navigate to a sequence you can see that it's just an extension function on a Tribble so any iterable collection anything you can basically convert to a sequence and then chain all of the wonderful methods that you have when you're doing method pipelining so what happens in the cases when you cannot have an interval to begin with for that we have other functions as part of the standard library namely generate sequence which has two versions one of them taking a seat and then on that seed you can do whatever you want and then from there again filter and all of this again will be lazily evaluated okay so there's two ways to do it as sequence or if you don't have a collection to begin with you can use the generate sequence okay now in the previous thing you saw type aliases or am I still too loud oh oh you're scanning okay right so in the previous one you had type aliases a one example of when you want to use that is for instance that that you said you know I want to have a handler that is a function that goes from string to string for instance right if I knew how to write Kotlin code and or forget it I don't and that is one use I actually don't like that use as much because one of the things that I like around Kotlin is the discoverability when you look at a function you exactly know what the parameters are so when I look at a higher order function and I see int of Intuit I exactly know what it's going to take I don't have to introspect the type to I actually understand what it's going to take but one other useful case of type aliases is for using it with deprecated so how many of you right here api's and you ship those api's to your customers even that's internal and you'd love to break your api's and then you know what you can do you can actually sell subscriptions on it and then that way you can always upgrade so for the record JetBrains doesn't sell api's so one one cool thing that you can do with api's is let's say that I have a class so let's go ahead and actually remove all of this nonsense over here so let's say that I have a class called customer right and then I have a main function that is using this customer so I say well customer eCos customer now tomorrow I want to come and rename my art customer to awesome customer right now if I rename this is going to break my api's so what I could do is introduce a new a ty values which is awesome customer right which is essentially a customer ok and then what I could do is come to my customer class and add the deprecated and say customer is now awesome customer right and see as soon as I do that when I add the deprecated the ID is going to highlight this and say this is a an awesome customer now but the good thing is that I haven't broken my API so I can do a phased upgrade right I can introduce the type Ali us have people switch over to that and then eventually in the second version remove that type alias and in fact if you've been on board with Kotlin for many many years I back when we we used to call interfaces traits I want to actually make out a t-shirt that says I was using Collin when it was traits we did this phased migration for Emory every M release we do this phase migration we first give you warning and then the next release is going to be a compiler error and you can actually use the IDE to fix this for you so you can say that replaces with awesome customer and what they replace with does is that now it gives you the magically alt-enter right so you now have the replace with awesome customer so that's one other use that you could use for type aliases to do a faced migration okay some things around inline functionings right so let's go to a higher order here we've seen it right so in this case one thing that we have with column is is inline functions and in fact if you look at a lot of the functionality in the standard library you can see that many things are in lines right you can see that a lot of these functions are in line and the reason for this well if you're who's familiar here with inlining right so for those not familiar inlining essentially what it means it's copy/paste right so instead of me calling when you invoke a function when you call operation instead of actually invoking and having all of the call stack associated with that what it's going to do is going to copy that function and paste it exactly where you're invoking it okay so it makes sense to do this with functions that are small you know do you don't do this with functions that are you know 200 lines of code now of course if you have functions that are 200 lines of code your problem is why do you have functions that are two hundred lines of code not the inlining now with Kotlin it only really makes sense to do inlining when your functions are higher-order functions not just general functions so for instance if I were to create a function here called fun my friend and this function has an integer and then I add an inline to it over here you can see that the compiler is going to give me a warning and it's going to say that my friend in line is insignificant the performance gained over in lining this function is insignificant in lining works best for functions with lambdas as parameters okay in this case it's not saying it because I actually have a lambda as a parameter so what this means is that when I create this inline function it's not only going to inline the actual call to this function but it's going to inline the parameter as well right that's where you get some of the benefits now inline functions give us another benefit as well which we'll see in a moment but there are times for whatever reasons namely for instance you want to be able to hold a reference to an inline factor to a high order to a function that's being passed in this parameter which you cannot do with inline functions the that are being passed in the lambdas all you can do is essentially invoke them so there are times when you want certain functions to not be inline which in this case you can decorate it with a no inline so if I have for instance another higher-order function here I can decorate the second one with no inline right so now it's saying that while inlining is applicable in this case because I have a lambda that is being inlined for certain cases I don't want it to be inline okay there's another fact there's another one which is called cross inline which I'm not going to give you the explanation of because for that you're gonna get a chocolate so go on go and google it so the inlining also gives us certain benefits right and it also changes somewhat a behavior and that's where we come to returns so here I have a function which is called containing function and it basically loops through a list of numbers and then it's going to do a return if I were to run this what do you think the output of that would be nothing no it doesn't return nothing it's a returns unit I'm joking who says nothing who says hello who says it's me no don't get it Adele oh sorry that was bad no okay yeah you've heard worse now oh yes and you have called Adele alright um yeah that must have sucked okay I'm so if I run this it doesn't return it doesn't print uh it doesn't run what did I do Oh G parameter G where's my G op no just remove that that's what happens when I do live coding okay so back to returns if I run this it's going to return nothing right it what I'm sorry what it doesn't print anything now before we understand why take a look at this example this is my inline function there is an interval of my for each and this is exactly the same as for each in fact if you navigate to for each over here right let's split vertically and then I'll switch back to returns you can see that my for each is essentially the same as the for each here which now died on me but anyway it's exactly the same trust me if I if I run containing function with my for each what do you think it's going to print hello or it won't print anything well if it's exactly the same as the other for each is going to not print anything right that was that was like a trick question it's not going to print anything however notice one thing I wasn't going to run this if I remove the inline I can't return right and this is what's called non-local returns the fact that this is returning outside the fact that it's not printing hello is because the return is returning from containing function why is it returning from containing function because for each is an inline function therefore it means it's essentially copying pasting the code in line and when I call return there's only one function to return with which is the containing function so what happens in this case well in this case you can't actually do a non-local return because functions the returns are only applicable directly when invoked like this they're only applicable to inline functions now what happens if I want to actually return to the containing function and not to the invocation of the containing function I use a label no this is not a go to please it is not okay this is not a go to it's a nicer go to it's an act so I use ad and AD is the actual name of the function these aren't built in labels right if I if my function was called my foreach then it would be at my forage and in fact you can prefix it with an label as well I can give that lambda label so I can say my label and then return at my label now if you're not aware in Collin we have lambdas well you know we've seen them right this is a lambda I mean where as my higher order if I write main this is a lambda so if I write higher-order F and then X to X plus something this is a lambda right this is a lambda which in many languages is called the same anonymous function in coordinates not we have anonymous functions as well this is an anonymous function right it's literally the same as in JavaScript so I have a function with no name where I can pass in the actual parameter name and then do a return in the case of an anonymous function it does perform a local return as opposed to a lambda so meaning that if you want local returns you can either use labels or anonymous functions okay yes what do you mean but you don't that's why I just showed you you can use for anonymous functions that's a that's a question best asked from Andre I guess not me there's there's a lot of reasons that we do some things in Kotlin some of them are for performance reasons others are for tooling take into account though a lot of times when people say to us why should I use Carlin if Scala is just like Kotlin but it allows me for more more things because the flexibility and the versatility that Scala has it also makes it extremely power of art to do tooling and performance wise it's not as performant right so there are there might be some reasons sometimes that we do it for for performance other times it might mean we're doing something because we're going to later add another feature that enable to be able to distinguish we're using this ahead of time right okay now with the inlining I said that inlining is good for performance reasons the other one is for reification of generics okay so if you're familiar with the JVM which you probably are you know that we have this minor little problem called type erasure right so what you can do with Kotlin is any inline function you can add the refight keyword to it and that will then allow you to do certain type checking on the generic type right so in this case I can say is input of T if I remove reified it says to me that I cannot do this okay so reification and if i remove in refight you see that i get the warning again right it says the performance improvement here is minimal because you don't have a lambda yet that does not appear when I'm using the refight because it does allow me to get some information at times okay one other thing we have in Cortland is well you have this in many languages but is variance covariance and contravariance so here's some code this is a mutable list of any and this immutable list of string and if I uncomment this is this gonna work yes or no I'll give you a hint the reason it's commented out is because I always check that this project compiles before I do the demos so it's not going to work why is it not going to work so I have a you know a string is a subtype of any but variants it's typing variants but why doesn't it work explain to me why this won't work right and that's what this is saying but yes no I'm not saying how to fix it I'm saying why doesn't this work okay yes yes and imagine imagine a much easier example for you to to see this it would be very obvious as if you're passing a mutable list to a function and you pass if a function of type any in your passive type string the function is of type any so essentially inside that function you could add anything to that list right because it's off type any and yet if you're passing in an array of string you can't add a number to a an array of string right no I just told them the answer I've got better ones for chocolate thank you I will is it is it is it dark chocolate or is it milk I don't want it so now this does work why does this work because it's immutable right and by default in Kotlin list collections they're all immutable as opposed to mutable that's why you have to write beautiful okay now in column we don't have we have call site variants but what you can do is you can declare certain types like this list here this list is if you go to the declaration you can see that this list is contravariant right which is indicating that what we've just done is possible and in Kotlin this is expressed without okay so you have out and you have in so we have declaration site variance which means that we declare the the covariance or the contravariance of that type at the declaration site you also have you site variance when you're interrupting with java for instance or in a specific function you can call you site variance but generally in Kotlin you do declaration site variance which means it's great because i don't have to have this question mark extends of all this that we do constantly in Java the rule of thumb here is really simple is if your class is only consuming then it's covariance and in fact the IDE can tell you it says that you're only consuming here so you can add the in to make this covariance if you're producing then it's going to be contravariant and you would add the out okay so to summarize you have covariance and contravariance you can declare it at the decoration site and you can also use it in specific cases on call sites now let's get into some of the other things around column which is dsls okay so let's do some coding here so how many are you familiar with DSL so domain-specific languages dsls are awesome ddd me Scott I don't know why Ross Scott go to ok and that's how we name things I'm from Spain I didn't mean that as an insult no and on one time I was going to I went to come I went to a company before I joined Jabbar I was doing consulting and I went to two I tell you this story because this is really really true I went to a consulting company and I was doing the code review and they had a function which was called so anyone speak Spanish here okay you all speak Spanish so it was called fetch a Manolo write and fetch her Manolo fetch a means date and Manolo is Manuel a name and I said what is fetch a Manola and he said it's a function we've written for Manolo because Manolo wanted the date in this specific format and I said but there's there's two Manolos here and they said no he's manual which is short for Manolo Manuel and this one's Manolo I said so what happens if you want a variation he says well we'll just call it my knowledge who write and I kid you not this is the code that's out there anyway so you all know about function extensions in callings so I can write is same as value string and then I do for example this equals value right and if again I I used to know how to write Kotlin code there you go so this is an extension function so I can say now or this is same as this right and I can do this in infix notation as well which I can just write it like that and get rid of that and the best part about doing doing demos in Kotlin in IntelliJ is because I don't even need to know Kotlin I just hit alt enter and I can get that in in fix and now that is awesome because now I can call this an infix notation and it starts to say oh this looks nice it looks like kind of like dsls right or our BDD okay so this is the this is the typical thing that you see in Kotlin right now DSL is go a little bit farther with cotton and what we couldn't do is let's try and create for instance a DSL that allows me to like do some creative framework around web developments how many of you are familiar with Express Jas or Ruby or Sinatra and stuff like that right so I want to basically create a function that has for instance a get that takes a path of type string and then takes a handler right and the handler is going to take for instance a request which is an HTTP request and a response and it's going to return unit and then I'm going to have a class request that for instance takes property of type accept and I'm going to have a class response that takes for instance property status code of type ends and of our content of type string right so now I could do something like get get home they're now in Cortland remember if the last parameter to another to a function is another function what can you do in Kotlin while instead of enclosing it here you can enclose it outside of the brackets right so I could enclose this over here okay okay and let's go get let's rename this to get root for instance okay why is that giving me an error the what requester oh yeah okay so yes so now I've got to do request response and then I have to do for instance if requests accept echos application JSON right then whatever like for example response content equals some JSON right and I love escaping key by the way you know how to write JSON in IntelliJ right alt enter inject JSON and then you do alt enter edit JSON fragment and then you do it like that you don't sit there and do escaping of characters okay so now this is nice the problem is that I have all of this horrible request response and the curly braces and all of that crap and this looks kind of sucky now what I can do is I can replace this with handler for instance right create a type called handler that handler in turn takes a request object and a response object right and then what I can do is since in Kotlin I could potentially if there's a single parameter to a function replace it with it I could get rid of the explicit declaration here and then this one prefix it with it right and then request would become request and response would be become response okay now that looks nice but again it's that it it's that wretched it that I want to get rid of so how can I do this I want to do just like if request how can I do that so you're all familiar with high order functions right higher order functions are what functions that take other functions or return functions what else do we have in called in apart from functions we have extension functions so why not combine the two why not create a higher-order function that doesn't just take a function but takes an extension function so what I could do is instead of this taking a function I can say that I want get root to take an extension function and the way you do that is by prefixing it with a dot similar to how you declare an extension function so now I'm saying that root get root takes an extension function now given that this is an extension function over here this means that this lambda is what it's a member of handler since it's a mammal of handler what does it have access to it has access to properties of that Handler meaning that I can get rid of it okay and I have my nice little much nicer syntax here okay following me good now this is also nice but I want to go one step further what if I want to do something like that what if I want to do something like that right content now let's follow the same pattern the problem here is that response is now what it's a type and essentially what I'm doing here is I want to do what I want to invoke a type right because this is this is a lambda so I'm saying how can I invoke a type that's not possible actually it is in calling you can create a class foo and then you can say I want to create a new instance of foo right and then in foo I can say hello and then this will say squiggly and I'll say no and what I'll do is I'll create an operator that is called invoke so that now allows me to invoke an instance given that I can invoke an instance there well why don't I just do the same thing here why don't I invoke an instance how do I do that well what is response response is a type so I have to do is create an operator invoke for the class type and I'll just tell IntelliJ to do it for me now comes the question of what do I pass in its parameter well what do I need here I need content what is content it's a property of response therefore I create this as an extension property to response meaning I now have my content okay and that's how you create their cells in Collin okay now this is just one sample DSL and the beauty here is exactly what we've seen is that when we talk about DSL people quickly single how I'm not going to create my own HTML no you're not the beauty of DSL is the small DSL that you create across your application right if you combine this something with Alberto's workshop around the domain-driven design what is one of the ideas behind domain-driven design sorry that's a different workshop about domain during design the idea is to have this concept of the ubiquitous language right whether whether where the business aligns with how you write code think the potential you could have here right you could have the Dutch tax office define their own rules in cotton it's like mind blown I was actually at the Dutch tax office and I told them this so and they said they're gonna start looking at Cartland so there you go the deal was if I move to to Amsterdam I get like a massive tax break don't be cool I do it anyway yes anyway so that's kind of like the dsl stuff in Cortland right and this is where you can use this car and you can use this stuff to create wonderful little dsls for your domain-driven design for your configuration file for all of these things we've used this extensively so for instance in team city which is our continuous integration server we have now created dsl tool as allows you to define all of your configuration using cotton right Gradle has adopted this for the same purpose okay any questions yes in what sense would it be performance I don't think that it is appreciated I don't think it is like it's it would be minimal in that case I know I don't see an issue in terms of performance it okay quickly I've got a few minutes left right so I'll show you quickly some things around what is this thing that we're going to see karate yes karate okay how many of you have looked into co-routines and Colleen right Cole routines are great they're the best way to do things I'm joking um so okay um I don't have internet so I can't put my wonderful slides on but how many of you doing a synchronous programming right now how many of you do threads I love it JavaScript callbacks love it it's JavaScript part of the callbacks part right so threads are complicated we all know that pull backs suck because the problem with callback is that you have a function that call that once it's complete it will call back another function the problem of course we all know is that it's not just one function that function will then have to call another function as a callback and then another function as a callback and so on and so forth and welcome to the wonderful world of JavaScript which looks like a tilted Christmas tree right because when you put all of the little you know arrows like this it looks like a Christmas tree if you look at it horizontally right and then of course injury in the world of JavaScript do the normally with callbacks error handling is also problematic right so usually the first parameter in JavaScript by convention was e for error of course some people think he is event or for exciting so they don't even handle errors so in Coleen we've tried to take an approach to a synchronous programming and concurrent programming using this generic concept which within around since the 70s or if not earlier I think the 50s called co-routines right or suspend herbal computations under the covers co-routines are essentially the exact same thing as callbacks except you're not worried about doing the callbacks it is the compiler that is the callbacks right the compiler under the covers is creating the state machine making sure where the compat where when you when when in front of suspended function is called it can essentially resume at some point where it can resume all of this is taken care of for you under the covers by the compiler and the way that we've done it in cotton is essentially by adding a single key words of the language called suspend right and the see that the suspension the this function is over here is this key word here suspend and what suspend means is that that function essentially can be suspended in some point of time and then at some point resumed okay so think about a function that you can pause and resume right Cortines take this idea of having suspend herbal computations where I can call a function suspend it continue something else resume that function get the information back and so on and so forth and doing this a compiler level meaning that you do not need any primitives meaning that if you are targeting JavaScript with Kotlin targeting the JVM with calling you don't have to worry about one platform having threads one platform having not threads all of that is taking care of you under the covers by the compiler to understand how it does it it does it with lightweight threads and when I say lightweight threads I mean it so here is an example where I have one to a hundred thousand jobs which are essentially threads that I'm launching and I'm gonna do a thread sleep and then I'm going to print out a dot when that thread sleeps and I'm going to run this okay so I'm gonna run threads okay I'm gonna run this what do you think the results going to be out of memory yes and look at my awesome nyan cat thing out of memory unable to create new thread okay so I'm gonna do the same with co-routines and kolaches you can essentially see that it's exactly the same thing except instead of one two jobs a one tooth under oath I've created a list I've got this little thing here called launch that you don't need to worry about right now I've this thing called delay which is essentially the same as thread sleep and I've got print if I run this what do you think is gonna happen it's obvious right because if it failed there will be a really shitty demo so this is actually going to run and it will finish and it's printed out a hundred thousand threads right and in fact I can print out a million threads right and allows me to catch my breath and what this is doing is really lightweight threads right so it's suspending functions doing the work suspending doing the work suspending resuming back and it's doing this by using trying to do it in a way that is familiar with the way you already code so the main idea behind co-routines is that I continue to work the way I have usually worked okay with no having to learn about new operators with not having to learn about new ways of writing a synchronous code have any of you played with rx Java right so Rx Java the first time they introduce you to rx Java they say to you everything is a stream and it's observable and you kind of think what the hell did you just say to me right and the idea is that you move away from discrete value or you move away from you know into the specific set of values to a stream of values that you continuously can subscribe to using what's essentially an observable pattern right Rx is pretty much an observable pattern with a series of operators on top and if you have done rx you know that you have to have a mind shift to move away from one certain way of programming to a different way of programming with co-routines the idea is that you do not do that with co-routines the idea is that you continue to program the same way that you would in fact take a look at this code right this code is calling two functions and measuring millimeters is is a standard library function that just measures how long code some code is going to take and then I'm going to call function one function two and print out the result of one plus two this function has a suspend it's called this magical thing called suspend which means it's a suspending function and this one has a suspend as well if I run this how long do you think this is going to take one second let's run it it's going to take neither one nor two it's gonna take two thousand fifteen milliseconds which is slightly over two seconds so yeah it's gonna take two seconds the point being is that this is exactly what you would come to expect I am running a function and then I'm running another function the idea behind co-routines is that I continue to work the way I am then you're saying that what's the bloody point of the others because this is not running on the main thread it's potentially not blocking the main thread anymore why there's this thing over here called ROM blocking which is going to block but forget the name it's going to block the main thread until any core routine don't use so let me get to that so this is a suspending function right I can't just come and have a main function here that's if I take a main function here and I say function one it's not going to let me call it because this says this is suspending function so the function that calls this needs to be able to know how to handle suspension suspending functions so you can only call suspending functions from other suspending functions the main entry point to an application you could use something like ROM blocking or some other mechanism which you will see but ROM blocking is kind of like a helper method that allows you to invoke suspending functions the fact that this is doing this means that it's no longer blocking the main thread you had a question thread thought join is is essentially waiting for the threads right here there is no threat or join in threat or join in what sense is it different like in thread I'll join you are launching 30 threads right and then you're waiting for them to join okay but you have to add some at some point wait for the threads to join and you're launching threads okay in this case to the practical like the the in terms of the result it is not there's no difference the difference is that there are no threads here okay these are lightweight threads Otis okay but the point being is that this is top-down it's no magic because one of the things that we favor in Kotlin is that when you want concurrency you need to be explicit right and this isn't concurrent this is sequential so how do i do concurrent like this in concurrent i have a syntax called a sink and a sink is not a key word of the language a sink is essentially a library called part of the Kotlin co-routines library and I think what it's doing now in this case it's saying that yes this function is now a synchronously cold so in this case it's going to run this concurrently meaning that the time is going to be one second right if you're familiar with c-sharp this is would be similar to the a sync await in c-sharp the difference is that here I actually can get the value as opposed to getting a task and then inspecting the value of that task and you can do some cool things with code routines like for instance even have a synchronous calls that are lazily evaluated so for instance here I'm defining one function one one function two and then I say result a wait and result wait just like before the difference is that I'm passing in a parameter called lazy what does that mean that means that it will only initiate this co-routine when it is needed which means when a wait is called meaning that in this case this would run two seconds right because until a weight is not called here it doesn't actually need to call it okay so you know co-routines yes the common pool so the co-routines use this lightweight threads so to speak and the you can launch these in different contexts context so common pool is one like a common pool of thread so to speak that you could launch this in and then there's different parameters you can have for example unconfined meaning that I you know it doesn't matter where you launch it you can launch it in one place and resume it in another this is essentially restricting it to a specific common pool you could also create your own threaded context and have it associated to that threaded context the point being here is that can I go two minutes overboard thank you the point being here is that I should have done this when I started launching Android studio actually now I should have launch the emulator before I even flew out from Malaga the point here being is that when you're launching a khole routine when you pass in common pool I can actually pass in other things are you familiar with our ex Java so subscribe on publish on kind of similar and I can actually launch on the UI thread as well right so here's an example this is like this is it for me for Android like I don't I know nothing more than how to launch this app in Android ok and this is the only time I ever open up Android studio so this is Android this is an application that essentially is launching Fibonacci on the main thread so to speak right and it is calculating Fibonacci sequences on the main thread and every time I click this it is calculating a Fibonacci sequence right and you see that the UI is updating and when I keep clicking this it keeps updating and it's updating this on the main thread so I don't even have to worry about that because it is taking care of making sure that this is coming back on the main thread so that's the context parameter that you're passing in yes similar yeah okay so yeah Cora teens are a separate library that are ship that's calling co-routines when you try them please try them now please use them when you first try them the ID is going to complain and say this is a experimental feature you can see that it says experimental fix that if I just say there you go you just add this and then no longer experimental everything's wonderful the the reason that we made that experimental was because marketing wasn't involved in its a completely wrong word we are it's completely semane tained we are we are using an introduction in fact there's a new framework that we've created from the ground up for calling web framework called Couture which is using co-routines from the ground up we're using an in production code we will maintain it so don't worry about that experimental flag just ignore it it's not there it's not part of the standard library as part of the library called co-routines Kotlin X called Linux or co-routines the only thing we added to the actual language itself was that keyword called suspend okay [Applause]
Info
Channel: GOTO Conferences
Views: 14,007
Rating: 4.9574466 out of 5
Keywords: GOTO, GOTOcon, GOTO Conference, GOTO (Software Conference), Videos for Developers, Computer Science, GOTOams, GOTO Amsterdam, Hadi Hariri, Kotlin, Covariance, Contravariance, GOTO Night, GOTO Nights
Id: 1KldcFc7HCY
Channel Id: undefined
Length: 55min 32sec (3332 seconds)
Published: Thu Apr 19 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.