Why Scala? ...by a hilarious Indian guy

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Is there any particular reason he brought in all of actors instead of doing some sort of parMap over the list of IDs? It feels like actors gave him the sort of boilerplate he wished to avoid.

👍︎︎ 2 👤︎︎ u/kqr 📅︎︎ Jun 25 2013 🗫︎ replies
Captions
thank you I'm going to talk about Scala one of the things I would ask you to do is to ask a question anytime you have one best time to ask a question or make a comment is when you have it so don't wait until the very end I'm going to talk just a little bit about Scala maybe you'll hear me talk for about five minutes or so and then I'm going to sit down and start writing some code and we'll kind of take the code along and see where it goes so the first question of course is you know why why do we care about Scala why should we be interested I'm sure there are a lot of stories as to why we should do something like Scala but what excites me about Scala is about a certain number of things that has happened around this we are not in over fathers environment anymore whether you like it or not you've been dragged into this war of multi-core processors and essentially what this means is that writing multi-threaded application was already hard on a single processor multi-threading is more multitasking and let's give credit where it's due Java did something wonderful you know probably a lot of you are old enough to remember this when you program in a language like C or C++ or even languages before you just could not use the same set of libraries to write code and if you had to write multi-threaded code you had to switch to a different set of libraries it was painful so what job I did really wonderful for us was it gave us this beautiful concept of write once run anywhere are some of us like to call it as write one's debug everywhere but the beauty of this is we were able to use a consistent set of API across these different platforms and that was great but when everything is said and done what we have on our hand is a fairly low level of abstraction and when you are dealing with an object we have to deal with a thread safety but that was only half the story then we have to deal with visibility of data the certain change done by one thread may not even be visible to another thread for a long time or for never for example we have to deal with concurrency thread safety and concurrency what's the difference that safety is to protected concurrency used to make it available and that was pretty hard so eventually one of the feeling I developed was that if you want to create a multi-threaded code in Java you gotta be God and I'm not one I'm a very mortal human being it's extremely difficult for me to manage that level of complexity in creating application now where this gets even uglier is that now we have multi-core processors on him and now multi-core processors threading is on steroids we got many threads attacking this object our data and how do we handle this so what we need is a higher level of abstraction I got an email from a guy and I thought this email was very funny but I'm sure he didn't think so and his email said hey venket we got this application it works fine but last month my company deployed this application on a multi-core processor and all hell broke loose and then his email goes on to say don't tell me to do the right thing because I already know it and I cannot do it what I want you to tell me is tell me the quick fix what's the simplest thing I can do to get this application running on this multi-core processor and I wrote him saying oh it's very simple just walk up to the Machine and turn off one of the cores and everything will work fine and the point is that we cannot just deploy applications and then expect them to work it is going to be incredibly hard to get them right this is where we need a solution but here's the good news the solution has been around for 50 years and I say that's a good news because I'm not a fan of trying newfangled things I don't want to come here and say hey look what we found yesterday you want to give it a try no we got businesses to run corporations cannot rely on something that's newfangled are discovered last night this has been around for 50 years academics has worked on it there are research projects that's been on this and there are commercial tools and languages on this the only difference is that these were not available on the JVM the Java Virtual Machine so what scholar does I call scholar as an old wine in a new bottle it really brings well through and practices and methods onto the Java Virtual Machine and the beauty of this is you can preserve your investments on the Java Virtual Machine you got applications running on the JVM you don't have to toss them out you got libraries built on the JVM you don't have to toss them out you've got experience built upon the JVM you don't have to toss that out but yet sitting right where you are you could still reach out to some of the capabilities of this functional style of programming and make use of it in the java virtual machine and that's basically why Scala exists it is to give us the power to contend with this beautiful power we have on our hand in a prudent manner so Scala is really essentially when everything is said and done is simply a language on the Java Virtual Machine it's a language that's not fully functional though I would say it's a bit more pragmatic while functional programming is extremely powerful I'm not a fan of all-or-nothing proposition generally while that may be great for most of the things doesn't mean it's great for all of the things so what Scala gives me ability to do is to mix and match based on my desire and the needs in my application so think of scala as a dial like a radio dial you could take this all the way to the left and you would be doing imperative coding like you are used to in java or you could take this dial and go move it all the way to the right and you could be doing functional programming like you're doing Erlang or haskell and so on for example so you have this power of selecting whatever is your comfort level in terms of the programming style and you can pick and choose what makes the most sense so what's what's really special about Scala are quite a number of interesting things that really Scala offers for us one of the very first things that you will notice with Scala is conciseness now a lot of languages are around there but languages like Java remember the time when Java started out as a simple language I'm sure most of you read the book that said Java is great because it's simple and I call this the politics of programming languages the guy who wants to run for office what does he say he says a car and government sucks bring me the power I'll make your life better 40 years later the same thing we hear but just the other guy is saying but the guy who got elected right so Java said look if you want complexity and you want to contend with it be happy with C++ but if you want simplicity and productivity come over here to this beautiful world of Java we got it here and then what happened now let you come to power we forget all those things right and slowly we got put more features into the language and all of a sudden Java is no longer a simple language it's verbose it takes enormous amount of time and effort to get things done and we got to write 20 30 lines occurred to even accomplish simple things and so what one hand what we want is if you think about this for a second there are three things that are interesting on the JVM the platform right the Java platform and don't underestimate that that's why the real power is the Java platform has come a long way over the past 15 years it's one of the most powerful platforms out there improved several times over and then the next thing is the Java API the JDK and the libraries that's ubiquitous and powerful and then comes the last one which is the java language also known as the weakest link so the language has become the weakest link of these three things the java platform the java api on the java language and why not simply reach over and use more better languages so that we can make better use of this powerful platform and powerful library and so when you're programming language like scala you are programming the java virtual machine you are using the jdk you are using your spring libraries and other libraries that you create and yet you are using a language that gives you not just the syntactical advantage but also a different style of programming that will leverage the the underlying platform in a much better way for us to be more productive let's enough talking let's take a look at an example and see how this would work um let's talk about writing classes that's one of the things we all do as programmers in especial Java programmers right so how would I write a class let's create a write a class called you know public let's say a car I want to write a car class or a stock class doesn't matter what you write and then what you do next you say public class car stop right there and think about it how many times have you written a class that doesn't have to be public kind of makes you wonder isn't it you say this every time or at least most of the time 99% of the time and yet we kind of been a to the gum and say that's life in the big city that's why we got righted and we end up keep writing it right and then we want to write maybe a year so I say what private int ear and then he said oops I forgot I need to say final why not final be the default that would make it life lot easier right so we tend to forget that then I'm going to say private int miles for the miles of the car now I got to say public in to get ear and then of course this has to say return ear then I've got to write you know public end you know get miles you all know where this is going then you have to write the set miles method and then once I finish writing the set miles method you remind me that I forgot to write the constructor but you know what it's only time for a coffee break I'm tired you may argue hey man kid come on grow up you don't really type this code we got fancy Ige's to do this I would be in this beautiful eclipse or IntelliJ I'll click on this button and there you the code just appears in front of you think about that for a minute do you want a complex lung language and then complex I des and tools to manage it right that doesn't make any sense I don't want to see the junk in front of me even if ID is do it that's called IDE vomit I don't want ideas to be vomiting on my code I want to clean it up get it out of my sight I don't want to see it why if I don't see it I don't have to maintain it if I don't see it it doesn't distract me so I want these things to work automatically behind the scene and I didn't even write the constructor in this code as you can see but I'm going to write exactly that code with the constructor in Scala and how do I write it so I'm going to say class are and I want this to be a integer but I want this to be a final value Val ear is an integer and I said it's a value cannot change a VAR miles is an integer so notice that I wrote this class and I declared that the car has a year and miles what else that's it you say hey I need to declare eras final you did I want to declare miles as a variable you did I want to get her for the year but no setter for the year done what about miles our getter and setter done what about the constructor done what else can I do go home take a break you don't need to be working hard to do stupid things you wrote a class it's done that's conciseness right there and the story so four little things that we do we don't need tools to do things languages have to absorb those things for you and that's exactly what this did by the way if anybody is courageous enough to sit in the front row there are seats are available here I don't know why everybody wants to go back but but that's your choice it's here if you want to come down here um I'm a good guy I don't I don't get hostile yeah please listen getter is very good question so scholar doesn't Billy javabean is such a sad story javabean was you know the day they announced Java Bean they said hey you are not just a Java object you were a Java Bean the Java Bean is like really what does that mean well you have properties and the bean got excited it's like cool water properties well you've got a field and you got a getter and setter that follows a special convention and the bean was about to open the bottle of wine but it said but how do people talk to me well by calling the Gators and setter methods of course and bean wasn't depression ever since it's like you cheated on me this is no power at all I'm just another object you're just putting lipstick on the peg Scala said enough of that no need to do any of that just make those getter and setter call it directly as a property and we'll deal it as a property so the answer is no scholar doesn't bother to follow javabean convention but is they okay that's cool rank it but I do need to follow javabean convention because I got some Java code over there that needs to talk to my class no worries you can put a Java bean property annotation on the property and then Scala will spit out the getter or the setter as appropriate so you can make it do it with the little price but it discourages you from doing things that doesn't make any sense lutely so in general the ability whether it's a good practice or not to create multiple constructors would be dinner Oh awesome question this is even better so the question is hey in Java we create multiple constructors how do we do it pretty pretty good question because I said the main constructor is already over so stay with me for just a second I'll come back to it because all this doesn't matter if this code doesn't work right so let's go ahead and give this a shot so I'm going to say Val car equals new car and I'm going to say this was created in 2010 let's say the mile zero I'm going to print car dot year to print the cars here and I'm going to say print card art miles to print the miles of the car so it's just a little code I wrote and you can see it printed the eora printed the miles for you but it also wrote the constructor for you already what's really cool about this is I could put methods here I could say drive and I could say distance which is an integer and I could basically say here I want to drive this the distance that was given so I could come here and say a car drive a 10 I'm driving this car 10 miles now I say car dot miles and print the miles it better have moved 10 miles and it did but what's interesting though here is the code you put within the class as you know belongs to the class however rather than writing functions if you start putting statements within the class so I'm going to say here a creating car now when I run the code notice that it called the creating car so in other words the code that you stuff into the class becomes part of your primary constructor which even aggravates your question now okay then where is the other constructors so Scala has what's called a primary constructor but it also has those called auxilary constructors you can write as many constructors as you like by writing methods within the class so I could say I want to give maybe a year over here and then maybe the miles is going to be assumed to be a zero I don't need to give the miles maybe so I could write code like this but then here what i could do is i could go call back into my primary constructor if you will but what Scala requires you to do is that in order to avoid redundancy of code and also errors that result from it all the auxiliary constructors are required to go through the primary constructor so Scala streamlines the way you write the code avoids duplication of code and eliminates bugs not only that if you inherit from another base class then all the calls to super can only go through the primary constructor so that again channel eise's calls in a proper way so that it avoids eliminates these errors that can normally happen in the code so you can have primary constructor and any number of auxiliary constructors in the code it's a good question so that's basically what's provided for you within within Scala itself so you see how the classes are really cute when it comes to writing these it doesn't take a whole lot of effort it is concise so you can see that the code is very elegant rather than introducing ceremony now you may look at that code and say yeah but that syntax looks alien I've never written code in any language where the syntax did not look alien every language looks syntax looks alien but then once your deep years of this do it for about two or three weeks you don't even think about it anymore so never let a syntax of the language scare you away unless it's perl that's a different question so don't let the syntax of the language scare you ever just you know kind of engage yourselves in the idiomatic differences and the benefit it provides and and don't worry about the syntax because we'll look alien to you no matter what because you're so used to a certain language and you're just brain just cannot parse anything else until you get used to it so don't let that dissuade you from looking at a language but Scala also has a pure object-oriented Ness what does it mean pure object-oriented well Java gives you the split world where you have primitive types and you have classes as separate from each other well the problem with that approach is you got to be inconsistent in your API is quite a number of times let's think about this for a second if I were to write a Java code and I'm going to say print line 1.2 string of course in Java you'd probably say system dot out dot print line but if you say certain out dot print line 1.2 string what do you think is going to happen error right in Java you'll give an error because you cannot call to string on 1 because 1 is primitive you cannot call methods on primitive types well as here in Scala I'm going to run that code and notice how it printed 1 how that how did it know to do that so in Scala everything is an object there's no such thing called primitive type in scala everything is an object you say oh that's cool but what about performance if I'm going to deal with everything is an object I mean now going to lose performance you could but the guys who wrote Scala are smart they said if this object is not being used as a real object in other words if one is being used as an int int all over then very quietly it will generate the bytecode where it simply becomes a Java int under the hood so there was no degradation in performance at all in that case if you are actually calling a function on the number then it realizes gee this is not a primitive anymore this is an object so at compile time it converts the number into what's called a wrapper object in this case of rich int rich it under the hood converts back to the primitive integer at the bytecode level so you got the best of both worlds you got four really good performance on hand and at the same time the convenience and the consistency of treating everything as objects in your code as well so this gives you quite an advantage in writing code but remember one thing though even though you are using a different language you are still working on the JVM there's only one true language on the JVM right that's the bytecode so all this gets converted to bytecode at the end of the day and so it's all bonafide Java code where the Java is not the programming language admit in that context Java being the platform in that particular context so they run under the hood so it gives you pure object-oriented nism now not only that it means that as a result Scala does not have any static methods no there are no static methods I know some people are willing to leave the room at this point it's like no no no no please stay stay - you in for a second it's even better there is no static methods because static methods are evil have you ever why is it evil because it's hard to test it the context is hard to understand it is there all the time but in a JVM running in a web environment versus desktop it confuses the heck out of us have you ever want any and if you had an opportunity to teach Java to somebody those of you know the pain you bring these captive audience and say Java is a simple language listen to me I'm going to show you a simple example what do you do then it's a public class HelloWorld and the audience is like excuse me what is public the other guys like what is class they don't ask you HelloWorld that's bad students in the room if they did but they asked what's public what's class you say you know what you don't need to know that right now let's move on we're writing a simple code after all then you say public static void main that's it okay now I want to ask you what public in classes what in the world is a static you don't need to know that let's move on and then when you finish writing they're really scared this is simple but there's a lot of things I should not know right it doesn't have to be you the language is simple it's gotta be simple just say print line that's simple there's nothing more there that you don't need to know so don't write a lot of junk and say don't know that and then it's simple it's not really simple that's just cheating so in the case of a class classes belong that classes represent abstraction for a for an instance so you say class car and I'm going to simply put whatever is the content of the car your miles and so on don't care but I want to know how many cars I have maybe Toyota is interested in knowing how many of them are there out there how do I know how many cars are out there well what do you do normally in Java you say define or public static int get count right remember that well here you say object car so notice how I created an object car what in the world is an object car only look at this code for a second don't go anywhere else that is the way you create a singleton in Scala what is singleton most of you probably know what a singleton s but in case you don't know a singleton is a pattern that you take five minutes to learn and six months to get it right it takes an enormous amount of effort to get it right people do it wrong several times over the fun with singleton is go to somebody's code and say I got a singleton and then you say does it work and you of course it does and then point out one problem and in two weeks later another one three weeks later another one it's so hard to get it right what is one of the best ways to get the singleton taken care properly to leave it to the class loader class loader is the one particular thingy that can load up a singleton properly for you so even in Java the most recent recommendation is to let singleton be handled by the class loader Scala said if singleton is so important and calm and yet we keep messing it up why not make it a language feature so singleton is a language feature in Scala and that's how we're you write a sing this is one instance of this class that gets created that represents the class not the instance that's americlaps right it's its it represents the grouping of concept you want to put in the class it's a one instance of something that it could get creates but then notice I also have a class called car and an object singleton called car when you have a situation like this this is not called a singleton this is called a companion object so while your class holds the details of an instance the companion object ends up having the details for the class so what I would do now is I would say define you know instances count or maybe count instances count of instances and I'm going to write a function here that's going to keep track of these instances if you want to wire yourselves into a job a way of thinking count of instances 'is a static method so in other words whatever you would have put in a class before you still put it in a class whatever you put as a static method in a class before now you move it over to this companion object what is that called it's called separation of concern you are able to focus clearly on one thing and one thing well when you look at a class you're not juggling between instance variables and static fields and instance methods and Static methods you focus on the class you got one view of the abstraction whatever makes of this object if you want to deal with something that belongs to the class itself move over to the companion object and that has the methods and stuff like that that needs to be in the class level and so that manages that so it's a very nice separation of concern that's calliper whites for you please markable frameworks um because they are objects at runtime so they can be marked away fairly easily as well absolutely great point and that is something that favors testability quite a bit right and and that is something to think about and static is hard to test what is because it's an instance you are dealing with you could you could walk away and stuff like that that can be done pretty effectively so it's a very nice way of dealing with with pure object-oriented is provided by the language here for us you saw you saw how that would work and manifest very nicely now there are quite a number of things that are optional when it comes to Scala one of the things you did not notice me do over over the last maybe about 20 30 minutes is what I never hit the semicolon some of the Java programmers are addicted to semicolons we are forced to write semicolons in fact there is a proof just look at your you know hand there's a reason why your pinky is so short it's taken years of abuse of the semicolon right but if you really think about it what does the semicolon do other than hurting your pinky not a whole lot it's a ceremony which was not needed at all in fact semicolons really hurt a lot of things because it introduces noise in the code when you don't have Sammy : the code becomes light let me show you an example here so if I say class car and I have a car which is going to have a drive method I'm not going to implement the method here I'm going to say drive I'm going to say oh let's do this it's even better let's say turn and I'm going to say direction and I'm going to provide a string for the direction to turn and I'm going to simply say here that the car is going to turn in the direction so I'm going to say turning and turning and I'm going to simply put the direction over here that's all I did so I'm going to create a car so car equals new car right boring regular Java syntax you'll be tempted to write like that and then you would say car dot turn and then you would say let's say left and then a semicolon like this that's that sounds familiar right Scala says why the ceremony you don't need the semicolon so notice that got rid of the semicolon and the code still works and then you say okay but what's that parenthesis doing for nothing can I get rid of that sure why not and the code still works if the Oh Kevin K is there anything more we could do what about this parenthesis what's that doing there why don't we get rid of that right so I got rid of that he was not happy because he says if you're going to remove ceremony go all the way so why bother with darts what is the dot after all do you say isn't it confusing it is to you it is to me but not to the language the language says I know what you are doing as long as you are okay with it but then only look at the line number eight what does it look like it looks well okay if that looks like English I want to know which neighbor who live in just kidding it looks like a very like it looked like data isn't it somebody could give you a stock trading data they could say Stark a symbol and then a number of quantity notice data becomes code code becomes data as long as you don't tell them that they're okay with it so you can move towards writing internal DSL it's in a very lightweight syntax so you can suck that line number eight from a data file and run through it data becomes code code becomes data and you say what do I do about all the time and effort I spend in parsing enjoy there's beautiful you know weather out there you don't have to be sitting and writing more code to do stupid things we always do languages can evolve to that point please you have to have the file name called the same way as a classic okay so a couple of two questions were reading one in your question jobs required class names to be the same as file names asked why for no good reason I'm not saying that's a bad idea good of a good idea but there was no fundamental reason the reason really Java wanted that was when you go across the web and ask for a class they wanted to know which one you're looking at and loaded you know what that was not a source code issue that was a deployment issue and what Java did was it pushed that concern to the code writing time bad bad idea having said that however in Scala you can put classes in any file you want to it doesn't matter I still keep the convention that we followed in Java because it's a good thing to follow for other reasons so it's a convention not a requirement at that point however if you're writing a companion object then the companion object and the companion class are required to reside in the same file a good question is why I'm a huge fan of asking this question why it's asking why helps us to really get to the bottom and then we know whether it's essential or it's accidental and the reason simply is that a companion object can access the private members of a companion class and vice versa which is a clear break in encapsulation only if it's outside the file if it's in the same file you're in the same scope of things you are dealing with technically speaking it's much more manageable so there's a good reason to keep them together for that reason that's you know it's important as the right question then have the right answers so I'm really glad you're asking those questions because that's the way we probe and find these things so absolutely great question to have but that's the reason for having both of them in the same place please the coats like that no oh this one goes over here ah okay so what scholar does is because you don't have semicolon scholar has to do a look ahead and it does a few interesting things it says you know what you don't have a semicolon I'm going to continue to read and see if what you are starting on that other next line can be a standalone for its own to begin a statement if what you wrote can begin a statement then it will say okay then I'll end it here if it cannot begin a statement it says oh maybe you just split this line into two I will let this follow through so I'm making sense so you will kind of look ahead and say does it make sense to start the sentence with that oh yeah it does okay then this ends over here so it uses some of those little conventions to go through and in this particular case you know her this not Java syntax in Java you will say car obj equals in Scala that's not valid so as a result it says I'm still okay because you didn't really finish this statement you're still going but but don't be fooled by it there will be times when you think you've finished it but Scala says no the other one still looks like it's going to be over here and it may go against you so you got to be careful in sup but that's a very rare situation that happens most of the time if you follow good coding practices you would never be in confused state with the Scala it'll be quite consistent a new could be ceremony I like this guy he says new is ceremonial venket I don't want it so what you're saying you know what a customer is always right so basically in this case unfortunately because it's an apply met there are some other convention you had to follow and as a result you could ask him now where am I going wrong here car and car I'm applying the new car define apply let's see where he's heading out let me see good idea to read that or sometimes all over the Fontan see what do you see ah this start car of type object does not take parameters of course he doesn't take parameters but I'm calling the apply method so why can't you use the apply method there you go so the answer is yes but you have to introduce a bit more ceremony because of a java convention but you got rid of the new yes sorry no no that's that's that's fine but but there are other reasons for it because it needs to know whether you are referring to a class or you're invoking a apply method so there's a bit of a depth of a concept involved in there if you really still have to get rid of it there are other ways to do it but then that's not important for us to do right now yeah um so let's talk about imperative ursus functional style of coding what does that mean well let's talk about let's say I want to total elements in a list maybe you got a list of prices and you want to total up what the total price is that's what you really want to do how would we do that so I'm going to say define I'm going to say total and let's give them a list the list is going to be a list of integers and what does it return to us it returns a total so I'm going to say var sum equals 0 VAR represents a variable valve represents a constant or a variable which cannot change so I'm going to say listed out for each actually let's write it in a more traditional manner before the value I in the list and what do I do in the list some each plus equals I and when I'm done I'm going to return some I said I'm going to return some that orders nmf with the word return because return is optional and it's kind of funny but you may miss it whoa you don't have return but once you program in this for a while it feels odd to put return I'll tell you I have to still write Java code from time to time I've been writing a Java code and my mind completely switched over and I would say you know value I'll be staring and the compiler is like you're missing return I'm like what and then somebody's like make it you're writing Java it's like oh I'm sorry and then you put return so you can becomes natural after a while no need to put return but I want to total these values how do I do that so I'm going to say a total and what do I want to put total for I want to create a list total off one two three four and five those are the values I want to total up and it says the total is 15 hey what's the house this is from in Java code not much because this is imperative style what is imperative style mean notice how I created a variable called sum what would what would you do in Java into sum equal zero okay to be fair into some semicolon okay initialize this to zero fine then what do you do you say for int I you have to tell int to Java because it doesn't know right so you got to tell him you know just in case so int here Scala says that don't bother I know I is integer how do you know based on the context I know it so it in first the type so other than those two differences it's pretty much like Java code it's imperative type but I'm going to write it in a functional style and show you how we could write this oh please yes oh yeah so I'll come back to this in just a one second look at line number four we are constantly modifying this variable so that again this imperative we keep modifying variable what is this less than so that's a good point think of this like a for each statement in Java right Java into this for each in Java five right four is evil in Java the reason why you should not use four at all as much as possible right it's a for each is better in Java why because the for statement requires you to index through and there's a huge possibility that we said is it less than or less than equals to you we passed it for thinking for a minute anytime there is an operation to remove thinking it's a good thing to do right then we can focus on other things so even in Java you don't want to use a for loop you want to use a for each loop this is a for each basically it knows to pull one element at a time and run actually a method call a conjecture right oh you could do the two yeah yeah there are other multiple flavors of this available as well sure absolutely some please this is is assigning to I a good thing or a bad thing yeah I hit the two so no it's a Val you cannot assign to it that's it that's a beautiful question right because wherever things have to be treated as a constant it will a páramo look at list lis D on line number one you cannot assign to lis D if you if you really squint your eyes there's an invisible final there so Scala just the right thing in Java if I do it I change list tough luck we introduce bugs in code doing that Scala says internet don't do that it's a bad practice right it doesn't allow you to do that so wherever things have to be in most of the cases if you never told him what type it is and you never said VAR val you can safely assume it's a final it's a Val so so so Scala does the right things most of the time so that's a good thing um this please a good good question our answer is depends this list in Scala lists are immutable so you cannot modify a period so lists are immutable but then Scala says I'll give you two sets of sets I'll give you two sets of maps those that are immutable and those that are mutable if you don't ask for one what do you think it's going to give you immutable right because that's safer and that's better if you want immutable you got to specifically say please give me immutable and it's clearly visible to you that you got an immutable list or a set rather nautilus set on a map so most of the time it's immutable but then you can also get mutable thing's for certain select things excellent we wrote up oh yes please I in the for-loop you are saying are where we're at yeah no no because the list is not sequential by any means that we have not no no no well if it is if it has if it is a if it is something that you can infer consistently it can but in these cases that's not true so it won't and no as a result it will not be trying to do manipulations that point there it does a lot of optimization it is smart but it's not arbitrarily smart it is consistently smart right so the answer that's why I would look at it where it makes sense to do it consistently it will if not no Scala compiler makes use of extensive optimization so it does know what to do but it may not do what we think it should do because that may not be consistently applicable in other places that's where the difference comes in now we know the imperative style code here but how do I write this in a functional style of programming so what I'm going to do now is to write this code in a functional style what does that mean I'll tell you what a functional style is later on in it to add a little bit more but for now in a functional style we're going to promote immutable ID that's not the full story by the way but that's a good story to start with we're going to say it's immutable we don't want to change any value once we create it so it's a it's called assignment list programming so how would we do this so what I'm going to do is I'm going to define total let's call it functional and then I'm going to say list is list integer and what do I do to total these values together that's my question now so to total these values let's assume for a minute there's a reason why not many people sat in the first row because I pick on the people in the first row to be too much so I'm going to total up the age of these four gentlemen he looks really worried no I'm not gonna ask for your real age that's okay so we got a total age of these four gentlemen how do i total the age of these four gentlemen so here's the first rule of thumb assume that I have a post-it note with me but this post-it note has a unique feature it's a right once post-it note once I write on it I cannot change it I cannot be raised and change it so on this post-it note I write a 0 because 0 is the total age of everybody so far what's your first name Richard and I'm going to give this post-it note to Richard so what is Richard ooh Richard is supposed to total his age to the age he received and pass it down right so what is he going to do he says it looks like a 20 year old guy what does he do he takes 20 and adds to 0 and the new value was 20 but what does he do now create another post-it note right on the new post-it note he writes 20 what does he do with the question what I gave him throw it away this was a revelation for me one morning I was like John it functional program will really suck if we don't have automated garbage collection we kind of toss it out right so he creates 20 on this new post-it note what do they do passes it down the chain I'm making sense then what is the next person do Hays 20 add his own age to another post-it note passes it down the chain making sense we will put that in code but notice what happened or what did not happen in this example we never modified anything makes sense so what I'm going to do here is I'm going to say listed odd fold left fold left is a function that allows you to take the data and it's as if you're folding or rolling it down you're performing operation on one element at a time what is the first value I send zero because that's the that's the value of give to Richard right that's a value 0 what does he get he gets a function where this function has two parameters please don't worry about the syntax focus on the concept so what does this do it says I'm going to take two parameters carry over from the previous one and element whatever my element is so now what am I going to return from here I'm going to return carry over plus element that's the value that I'm going to return from this particular call so what would what would this do then so I'm going to create a list of 1 2 3 & 4 & 5 it better be the same result after all when the whole thing is done but what how is this different the first noticeable thing here is notice there is no assignment at all in line number 10 to 14 I never set a value when I call for left I send 0 to Richard what is Richard get Richard says oh you called me and you gave me a 0 for carryover and E is my own value he at 0 to 20 returns it what is the for left to grabs that returned value turns around and calls the function one more time it's a function by the way here and since 20 as the carryover e is the next element in the list takes the computational result of it and then carries over this is a built-in function within Scala for the list but this is a functional style I've completely avoided what a functional style is but I keep saying it but you can see the difference in the syntax and also the variable being so on one hand you notice it's pretty concise by the way it can be even more concise than this but I don't want to go there today we're going to just be happy with this and move on this code will just fizzle down to very small amount of code and you can do it fairly easily in Scala but I'm not interested at that part right now today but I'm going to focus on the functional aspect of things here so what is this functional style I keep talking about the first thing is assignment less programming you're not assigning variables over and over and over hey what good is that when you have signed two variables you got to worry about thread safety if you don't assigned to variables you have nothing to protect so you are much more free to use things the second benefit of functional style functions don't have side effect so what does that mean functions don't have side effect when functions don't have side effect multiple threads can call that function and you don't have to worry about messing up supports concurrency again so think of a function as a cylinder you put some stuff in the top it gives you the result based on what you sent in it doesn't change anything outside nothing outside changes set so it is very well-behaved and the data that comes in is immutable because of assignment assignment less programming so what's good about it you got what's called a referential transparency a referential transparency says I can take these functions computations I could move them around in my code gives greater privilege for JIT compilers and other compilers to optimize code movement but not only can it move up and down it can use referential transparency to distribute this across multiple cores are multiple processors it gets to know what can be distributed what can be computed simultaneously and you can grab the result and continue on gives let you can leverage that very quickly so functions functions are first class citizens what does that mean remember how you can create an object within a function and create a function within a function if you read a function anywhere you want to mostly so you've been middle of a function you can create another function an anonymous function link comes to life you can do that you can return functions from functions like you return objects from functions you can pass functions to functions like you pass objects to functions so then your application can be decomposed not into objects but can be decomposed into functions it turns out functions are the smallest grain of granularity not objects because objects have collections of functions we're even smaller than that functions so functions become true composition of your system and functions are higher-order meaning you can put them together to compose a system rather than putting objects together to compose a system so these are some of the capabilities how is this going to help how this is going to change our way of doing things let's go back to totaling numbers for a second so I'm going to say define total and I'm going to say list and I'm going to take this list of integer and I'm going to total these values so what do I do I'm going to say var sum equals zero and I'm not even using the assignment nature assignment less nature here so I'm going to simply say for a list dot for each sum plus equals the value that I want ho total so notice how I'm writing it a bit differently this time and I'm going to turn the sum I'm not using the traditional for loop now what's the difference a four is an external iterator you say next one please next one please next one please for each is an internal iterator you do the job of iterating I don't care but I'll give you the body of code to run for each element right now let's say we got this done and I say print line total and I'm going to give it a list let's say glister of one two three four and five one more and six one more time and I run this code it from finds the total I think I'm done I'm about to leave my good friend Richard say is ranked a good try I want you to provide me one more function a function that will only total even numbers all right Richard no problem how do I do that right another method there is a reason why God invented copy and paste so copy and paste it right and what do I do here I'm going to say total even and what do I do here I'm going to say over here if the value E is even then do the total excess let's see if that works so once I finish that part I'm going to make it work right now and so I'm going to say total even over here that's what I want to total and that should only total the even numbers in this list and it turns out it did I'll make it a bit easier on you by moving this up here okay so I think I'm done I'm about to go home Richard says uh excuse me I need one more thing from you I want you to total odd numbers oh by the way I also will need you to total only numbers greater than some number at this point wisdom has to kick in copy and paste will not improve only advantage would be job security but that's a job you would hate eventually to have right this is where can Beck introduce this concept called triangulation so triangulation is where go ahead and duplicate the code once maybe twice but then you see a common Ness emerging out of it then you pulled up the commonality and create abstraction how do you create abstraction normally in triangulation creating a base class right but that's heavyweight it doesn't have to be a base class why not just a function that will provide abstraction so notice what I'm going to do now I'm going to go back to this code I'm going to get rid of this total even because we duplicated that I don't want that what I'm going to do is total select values who's going to select Richard here's the one who keeps telling me every few minutes I want this I want that I'm going to give him an engine to select I would let him decide he tells me the predicate so notice what I'm going to do now here's the last selector you can call it whatever you want to call it doesn't matter what what is the list list is an object selector is an object but it's special what kind of object you think it is it's a function those are called function value in Scala so I say selector what does he take takes an integer what does he give see notice how the function is a mapping of input to output what you think is going to give you a boolean that's right give some boolean now what am I going to do here I'm going to simply say I've got a sum here but if only the selector e accepted it then do the sum notice how trivial this code is notice of syntactically it was no ceremony the day I learned this I cried that night I say it cannot be this simple I thought this has to take a lot of effort how could it be this simple it's got to be complicated right no it doesn't have to be and so what did this do it said I'm going to receive this value and I'm going to say if the selector says yes I will add it I'll always ignore it what's a sector it's a mapping of integer turn boolean that's all so now what do I do I come down here and say total select values because that's the name of our new function here right so your total select values and I'm going to give them a list all right but then after the list I give them one more function this function says I'm going to receive an element e where this element E better be nothing because I want to total all the values true so essentially I total all the values so the code still produces the result it did before but now I want to total only our even numbers how would I do that so I'm going to say print line total select values I said E but this time e mod 2 is 0 return the true of that that is going to end up selecting did I mess up what a picky audience fine okay so notice now that it is able to print the 12 but then Richard says okay link it but I want you to total only values greater than some number let's say greater than 4 guess what I'm going to do I'm going to simply say value is greater than 4 or you could say you know what let's just make it non ceremonial you could say whatever value give me a better Lee greater than 4 you can make it concise that way but what did you do just now you made the total select values highly reusable that function said I'm going to do the totalling but you are going to tell me what the total the values and what to select again don't let the syntax bother you look at the concept you have on hand right that's functional ability to decompose the system into smaller functions so again the thing that kind of makes me feel a little I'm doing this type of thing is in again in terms of testing when you have the ability to pass in dynamic behavior into a function testing that function to me that becomes like how do you test every permutation of what they can toss into it um it's very simple if we work for a company where we compile code and ship it we are in trouble but we have the culture of compiling the code and running it before we ship it not a big deal so I'm not of the belief that unit testing is important I'm of the belief that unit testing is very important in combined combination with integration testing and functional testing so you can actually I would argue this code is even more testable because I can throw in must behavior into this code by marking this function at unit testing level and I can fortify your function saying your function is rock-solid even if I send misbehaving functions unit testing can cover that then during functional testing you got different scenarios you may say hey we're doing stock selection but here's the predicate he says no my predicate is different he says my predicate is different well we got three integration tests for them whereas your functional test says I'm also going to test for odd conditions that I didn't expect today to happen but potentially could happen so you got a double you know power on your hand so this actually lends itself even better to testing but we have to have the discipline to do it yeah we just from an API standpoint those years you're driving an API you don't know what functions somebody's got a point on acid so but but this is not a new problem right any time we use dependency inversion we've always had the problem right so if you really really want to close it you could even here it's not that you're mandated to write code like this but if you do want dependency inversion it doesn't cost you an arm and a leg and a spring to do it right that's the difference here I know I know maybe I was overthinking it and I think it's always no that's a fair question by the way and a lot of times even if I know it it helps to assert a certain understanding so I'm not bothered at all with your question it's it's a good question to have please correct you cannot modify the list period it potentially could right it potentially could but doesn't mean that that's the way we're going to do it right so this is something very important to think about you don't okay if somebody comes to you and says hey I know uh see our programmed in C for 20 years I'm going to go read a Java syntax book and code what does he do he write C code in Java so what you are saying is hey if I create a huge list and manipulated yes but that's not the way we were designed the application so you remember how you took about what a week to learn Java and then ten years to know how to design with it or maybe more we all do right I'm so learning that trick of how to do good design even though syntax comes quicker similarly designing a concurrent application or a functional application or both is a separate skill we have to do spend time gaining we cannot throw a data structure from a traditional code onto a functional language and say go do it like I said yes you can make it mess up yes you can make it fail you can make it suck but why would you write we would design it so you can leverage it and not make it suck so we cannot design application the same way with the newer language this is the story of this guy probably heard the story there was this guy driving on the road and he saw this guy using a in a saw man what are you doing I'm cutting the tree with the saw look at all the tree I got the cut and the guy said you know what I've got news for you here is a saw it'll solve problems you'll cut all the street 20 minutes and he goes away next day is coming back and the guy is still using his old saw hey what happened to the chainsaw I gave you why didn't you use it are you crazy that didn't work he said show me how you used it he took the chainsaw and did that and he said oh dear you forgot to crank it up this is how you do it right here's like oh you didn't tell me that so absolutely right we got a new tool on our hand we got to use it differently but that doesn't mean it comes naturally give a chainsaw to somebody who doesn't there are people around you you don't want to give it to you right but there are people around you who will be able to man it that's why we have to get trained ourselves for those skills to use that then we are more productive but you cannot just take a chainsaw and give it to someone who's never used it and say you know go at it he's probably going to card but not a wood right so that's why a please so when you're adding an element to a list and it returns renews thank yous of any sort of optimizations like closure doesn't persist absolutely well so what so what happens when you add stuff to a list because memory is a concern and performances are concern you're not really adding to a list you're creating a new list however that did not go around and copy the entire list also what it did was it really created another head you cannot add easily to the tail because of that performance concern which again changes the design of your system but it will create this new element the new element will point to the head of the old the list and then your list pointer will point to the new head so the older list in the new list coexist you say oh my goodness what will happen if things change because they don't change you can optimize on these things it me already helps you in this field so good point I'm glad you asked you know as the broad brought that up because that kind of optimization happens as well but then we also have to do other concerns on top of it so that we don't duplicate our data over and over Moo please but right good question so Scala says as much as possible I will determine the type for you but if you are defining a function at a very top level or a root of a tree of dependency you need to tell me the type so in this case I said it's an integer and that piece of information is the required Scala requires you to do it you could generalize this you could write this entire function as generic and say you know list of T and this is taking a T and giving a boolean sure but you have to specify type at that level however notice I never specified the type after that because there is enough information for Scala to talk about it let's talk about that for a minute if you will so we talked about the functional style but let's go to Java for a second if I say string STR equals hello so I define this as a string we saw this now I'm going to write a Java code if I say Java array list I say list equals new ArrayList and then I say let's start add one and then I say let's start at one point oh we know we're in trouble here because we're putting all kinds of stuff into this list you may say Oh venket this is not a problem we know already we have a solution for it what is it generics right so absolutely we can put generics so I'm going to say integer and then I'm going to say integer over here also right integer so now the compiler will not compile this line of code yeah we've done it or did we you could do this you could say array list the equals list derp dart you add 1.0 what will happen it'll compile it will produce a bytecode when you run it what will happen potentially a class cast exception when you pull stuff out of it when you pull stuff out of it you're going to get a class cast exception here's a way where we wait we have generics it gives us type safety why am I getting a class cast exception this is worse than what you had before because you didn't say integer ones you said it twice when you say it several times and they don't get it what do you think Java has the intelligence of a monkey it doesn't matter how many times you tell it it doesn't get it so in Java when they said typing they meant your fingers what are you doing typing what I going to do this afternoon more typing never use these words Scala is statically typed like Java that's an insult because Java is not certainly type period it just fooled us right it's not statically type it's sad in Scala var ster equals hello so I created a hello and I'm going to say print line ster so I created as a variable I printed it now as a stir equals hi a change in print line stir notice what it did not say at no point did I tell Scala you are using the string I'll be honest with you when I started learning Scala I did not write code like that I wrote code like this all my Scala code was fully type with my hands that was one morning I was getting out of my bed when I suddenly realized darn it you've been doing it wrong and I heard my heart was pounding how stupid was I so I ran to my computer opened up one of my Scala code and I started removing type information and I started running the code while the code was running scholar was laughing at me kid finally you figured out what I am about it is not about typing in code it is about type inference you type less because it is more typed in a language that is typed less you type more because Scala is well time you type less you may sequence what I'm saying playing with the words here physically typing you don't need to do that so now if I say over here stir equals one prinster Scala says excuse me you can do that type mismatch I found an integer when a string is required by the way don't misunderstand this as dynamic typing this is not dynamic typing if this were dynamic typing line number two and line number four would have run before this blew up this is a compile time typing you say Venkat venket where did you type where did you compile compilation happened when you run a color code you can run it in one of two ways you can take a Scala code you can run Scala C like you run Java C and then you can take the bytecode and run it but if you're writing a small piece of code you don't have to go through that ceremony Scala says I will do that for you so if you say Scala and the and and the name of the source code Scala will create the bytecode Scala is never interpreted Scala will create the bytecode grab the bytecode and run it so you don't have to spend more time with these ceremonies all right so that's what happened here at compile time it said this code won't work and point it to it so the next thing I want to talk about we talked about a functional typing and with a style we also talked about the typing and the and the capabilities I also showed you function values I'm going to only talk just a little bit about pattern matching not a whole lot you can do pattern matching to match against various streams of data that come in suppose you're receiving a message stream with stocks and trading and symbols you know to sit there and do a lot of work you can put a pattern matcher you imagine a pattern matcher a coin splitter right our coin what do you call that you know coin sorter right so you just put coins over it it falls in the right places think of a pattern matcher similar to like like that you put case blocks and it filters nicely when you write it the only problem with using that is you won't want to go back and do any other way after that it's so charming when you do it that way it's pretty powerful I'm not going to spend time on it because I want to spend time on other things for you today in hitting here and I'll show you a little bit of that later on with the XML maybe maybe I don't know but I want to talk about traits how many of you are familiar with multiple inheritance okay a few of us the others know not to raise the hand you never say that in public right why do you want me here I like multiple inheritance well because multiple inheritance is like a gorilla it's so cool and beautiful when you watch it behind the bars in the zoo but you don't bring it home it topples everything over right and so multiple inheritance is like that well the good news though is that multiple inheritance is not a bad idea it's the implementation of multiple inheritance that's a bad idea in language like C++ we can use multiple inheritance in a very controlled manner in a very efficient manner using mix-ins or also known as traits in Scala let's look at an example here let's say I have a class that I want to create human a within human I'm going to create a listen method so listen and I'm going to say listen and I'm going to say a print line let's say you know something like I am and I'm going to put a name plus your friend so what is a friend a friend is somebody who listens right that's what a real good friend is so friend has a name and he's listening so now we say Val Peter equals new human and I'm going to say Peter over here now I'm going to say Peter Dart listen to listen and I run this code and I'm Peter listens but then we realize after a while we forgot one very important friend what's that dogs dogs are the best friend right man's best friend how do i implement a friendship in dog i got an idea how about inheriting dog from human and they don't like it so tell me what's the Java way to solve this problem interface visitor all those concepts right well we want to do this a little differently here notice what I'm going to do now I'm going to take this listen from here remove it from human and I create a trait called friend I created a trait called friend with the listen and name is a string in other words this trait requires the object which is going to mix this in have that property and I say extends friend nothing not not much difference right so I run that code and human is still a friend but the beauty of this is I can pass human to a function that takes a friend so define seek help and I say friend and I'm going to send this friend to this method so I say listen now I can say seek help from Peter so notice how I'm treating human as a friend I'm able to send it but what's the beauty of this the beauty of this is it's extremely lightweight and as a result I can easily say class dog let's do it up here so class dog actually let's say animal class animal has a name let's say string and I say class dog is also having a name but it extends from animal and the animal has a name but then I'm going to say over here Rover equals new dog Rover and I say Rover dot listen and seek help from Rover that will work obviously right because you never linked dog to the friend but you know the dogs are the best friend you could have they never interrupt you you are going home after a very tired work you know you say you've got a lot to unload about the day's work you start talking the dog intently listens to you right so we want to make that happen please and it depends it depends on which which part it is but here's the beauty don't put the type Scala will clearly tell you when it needs it right if you're in doubt don't put it Scala would say excuse me you need to tell me what the type is so that's the only time you want to put it do a certain extent yes but you cannot eliminate all the type all the time because there are some times when Scala cannot figure it out right so you're going to look at 1% of the time then 100% of the time that's the difference that's why it's still a statically typed language some point you got to specify the type and you could say oh but in other languages that's not the case Scala says it's not worth going that extent because it leads to too much compilation complexity and and error rate so basically what I'm going to do here is I've extended the animal from here but then I say width friend so I put the trait up here and I've said dog is with the friend and I run that now basically in this particular case what's happening here is okay so this is going to override him because this is a parameter that's coming from the base class that's what he was unhappy with so notice how I created a dog as a friend one more step I want to create a class oops a class cat cat has a name Val name string extends animal which has a name so now I say Val snow equals new cat that's my cat's name let's say now I say snow dot listen are seek help and since know what's going to happen it will not work that's because you know very well cats are not friends they stare at you they say I want to go back to work you're bothering me right you have a cat Joe here's a wise man Richard you have a cat anybody has a cat you he says you know what this is unfair hey here's he was he was happy until this point now he's offended he says this is unfair right well okay cats are still not friends but his cat is special so we got to go to his cat notice that classes don't have trades objects can have traits I will not talk more about this but I will just give you a teaser I use this to create decorator pattern the decorator just fizzled to a beautiful code this is something you would frame and just keep looking at it in Java if you want to use a decorator or some patterns you fall a committee and you go through strategies right you just do it it just works it's beautiful to build decorator patterns with traits it's just amazingly simple and you don't even have to have a single concrete class I like kind of feedback like that where the music tone rings and says yup that's cool so essentially the point is you can create abstract classes and then chain them together with trades and get combination of flavours of things without having to write any hierarchy of classes and then you say wave it let's run that again what if you mix two trades together and the traits have conflicting methods remember that's what drove us away screaming from multiple inheritance what Scala does is it does method chaining so it'll form the trains that's where the decoration comes in it forms the chain and passes the method one after the other from right to left is it right today right to left right and so it knows how to connect it together extremely powerful so I talked about traits what I want to talk about next is a little bit about XML so I want to create a little XML document so var XML equals hello / hello looks familiar right hey wait wait wait how long has excelled XML been around 97 that's what 1314 years still still one dot Oh beautiful isn't it if you live in a place for five years and don't commit any crime you're eligible for what citizenship xml has been around for 14 years and yet it's a second-class citizen xml says this is unfair you put me in a double code what why do we deserve it why can't I have my freedom and deserve the respect I deserve it has been accused but those are misdemeanors it's not crime like crime I mean a little tax flaw penalties were charged they paid it on time let's remove the shackles xmo is a first-class citizen X equals 5x equals XML why not anybody has a problem with it see you're the only one who had seem to have problem here so XML is a first-class citizen you can put XML in code you can read XML and process it it is a it is a built in as part of the scholar XML LM class it's there you don't need Dom to process process it you can use XPath query on it let's give it a try so I want to go find out what the weather is right it turns out Yahoo gives me this information so let's go see if we can find that so I'm going to say get whether they are info and I need to give them a ID and the ID is going to be a string I'm going to give them so I'm going to say value are l equals Yahoo weather as you can see I type code really fast so Yahoo gives me this data I give them a URL we'll take baby steps to find it I'm going to go to Yahoo assuming my internet connection works and pull the weather data so what do I do I'm going to say a print line get well actually will not do that right now we'll do it a little bit differently get weather info for what for this city that I've got the ID for on him whatever city we'll figure it out so then what do I do now that I have the URL I want to go to the URL and get the data what are you doing Java for that new URL object and then what do you do get input stream then what do you do get input reader then what do you do get file reader or bufferedreader and then you put around that 2030 catch blocks it's time for lunch time does it work what do you mean it works I just finished typing the code it's a crime to be coding like that right it's a waste of resource I want to go get this how do I do that so start from URL URL import Scala dot IO and I'm going to use XML import Scala dot XML so I got the source and it's puts all the data make string and I'm going to store it in response response equals let's take baby steps don't mind that right response so I'm calling this code and say and go get this for me and I believe I call this as woid which is what I should call this one no problem so run this and what does that do it should go to the web and it pulled up the Yahoo web service two lines of code folks you still have a problem to deal with you got to figure out what to do with your free time but you don't have to spend that typing and having corporal tunnel that's there from Yahoo right there what does it say it says how Denver place near where I live or I'm supposed to live and then it says location and then it tells me the temperature I want to pull data from XML the minute you say that you'll see smile on some people's face yes two weeks in the timesheet in the air special consultants right they're like yeah I can not only two weeks in because a timesheet I will charge hours in the evening and eat their pizza so I want to get this data what do I do well XML response equals XML dart load string response print XML response now what did I do I went from a string to an XML nothing different so far but it's XML so now I say hey tell me XML responds XPath query location XPath query City you should know the XML structure obviously but that's no big deal you know it already right that's what I want to find out these two locations these two details that I want to pull from this and it helps to print sometimes otherwise you're staring at it's like what's happening Denver I want to know what temperature it is right now in Denver not yesterday not tomorrow now so what do I do comma x ll responds and I want to know the weather condition right condition and what I want to know is temperature and it turns out it's 33 degrees folks above freezing it's a warm day it's warm Denver 30 is worn by the way yeah believe me tell me three lines of code equals productivity if you want to write this in Java you could but the cows have gone home say I like that music this be a great group to video I love it you got real people with skills here man so absolutely right don't have to do that no need to write a lot of code when you can get things done quickly like that that's xmls first-class citizen merely scratching the surface yet obviously it's a lot more you can do with it right but now that I've gotten this let's see what we can do I want to go through multiple cities and get this information so I can take you to concurrency a little bit so what am I going to do I'm going to say let's do for some integer ID in the range of that I don't even know what this numbers are to let's say 9 I don't even know if these are valid numbers but who cares I'm going to go through this list I'm going to ask him to get me the details for each one of them I'm going to change it a little bit I'm going to return not the not printed but return it that's a tupple I'm just returning that topo tuple is beautiful it is just collection of data lightweight collection of data which is immutable those are great candidates to exchange across multiple threads because they won't get modified anywhere right so now what am I going to do I'm going to simply say here for this list I'm going to print line get weather info ID dot two string so I'm going to ask him to go out and get this data for me for each one of those cities in that list one at a time and display it it all seems to be Denver because different zip codes and stuff like that actually you know what huh at the go city yeah where it's frozen actually they're all Denver by the way but not the same Denver so would be nice to know a little bit more right so notice what I'm going to do here copy that and say reason so we're going to where in the world all those Denver come from that's the shocking news that there's actually more than one Denver in this country talk about namespace coalition so what's happening here it's taking time spinning the wheel come on you can do it yeah that's right that's for sure that's probably the case right it doesn't have a region I don't know what happened here bug fix it yep so we can go through and that's probably a little delay in getting the signal I don't know what it is we'll see so you can look through and get all these data but the problem as you can see is it could be slow hey there you go that took a long time but apparently there's a denver in ohio the two of them yeah one is not enough um there's one in south carolina that's the place to go Carla for cheap man maybe that was a different Denver at the time then and I asked for it it's really a warm day hmm Ohio yeah why is it wise to zip codes most likely those those IDs are zip code I DS it's quite possible that there are multiple IDs nearby so if you asked for the zip code you'll notice it's different the thing is okay this is still gonna take a little bit of time but I want to speed this up I want to make this kind current should we do it alright let's do it so I'm going to put a little delay here to see it and it is already slow maybe I should not put a delay if it gets fast will slow it down okay so let's say start equal and system dot nano time yeah exactly premature the optimization yeah so end and I want to know what how much time it took so let's say time and equal us and mine is start and this is a nano time so this should take you know what it's got about ten cities even if it takes one second it should take ten seconds but we'll find out how much time it took in seconds when it comes back nine point four seconds at the very bottom all right we're going to make this faster but without making it inaccurate incorrect and who's going to keep count of number of lines of code I'm going to write you'll do it for me all right can we trust him with the count okay so we got about twenty two lines of code now okay so here's what we're going to do see if this makes sense um I'm going to first of all say import Supes import scholar dr. and import scholar actor dot star or underscore are you counting those two lines and number of lines of code yeah a fair man okay all right so we imported yeah we we imported those two so what's an actor an actor is a thread that has its own building message queue an actor is a thread that has a built in message queue you can send messages to actors and you never get blocked you can receive messages whenever you want to and process it when you receive a message it runs in your local thread no coalition only thing you protect is what you send across the threads doesn't collide with each other sending mutable objects you're good what about visibility what about thread safety what about concurrency no worries about those things because Carla takes care of all of that behind the scene you are synchronization model just got simplified so what am I going to do see if this makes sense if it doesn't make sense ask me right away because it doesn't get better so what we're going to do is this I'm going to first loop through this and I'm going to ask him hey go get the stock prices so what am I going to do this for for our five guys in the front row are eager I'm going to give each one of them a CD name and say go to Yahoo and find the data right so those are my actors let's say so what am I going to do I'm going to say actor and I'm providing a function value as you can see and I say go add it let's assume I'm not even interested in printing it out for a minute though you could but that's not what I want to do let's say so notice how I asked them to go get it so I could put them all in one line of code if I wanted to because he's staring at the number of lines of code I could do that so all that I did was I said actor please go find this better data for me well there's one problem they all go find it and then what did they do they tossed it excuse me when you are done could you please text it back to me so I got to give you my reference right so notice what I'm going to do here I'm going to say a caller equals self remember what this is this is a reference to your object self is a reference to your actor so every code runs within an actor so what am I going to do now I'm going to say caller but you've got to send the message to caller there's a very highly intuitive method called bang so you bang the method over to him we're almost done we need to receive the data when it's done so I'm going to loop through one more time you could loop through ten times or whatever doesn't matter so that number is not needed but what am I going to do here I'm going to say receive case message print message so we're going to receive it one at a time as it arrives from those actors if you don't want to have a live lock I could say will the say within let's say three seconds or whatever that is reasonable for you you can put that number over here so basically we what did we do here we asked them to go out to the web look at all this data come back to us when the response comes back and there was one timeout but notice it finished within five seconds instead of nine seconds in this particular example I don't know why there was one timeout one thing didn't come back in three seconds maybe we can favor him a little bit more time and say go get it so that is an example of you see how with the time is different maybe I could put a delay there and you can see it more prominently but you already see it it felt that way right so you could at least a five-second delay in this case so this is an example of how you are able to send off these requests and then receive this data in a concurrent manner you can do more work here or so many times out exactly each request is sent out in its own different actor not thread an actor because the actor is a bit more than a thread and in here because you could have thousands of actors but only a few hundred threads so these are threads with message queue from the thread pool you
Info
Channel: Phsorx Phsorx
Views: 313,766
Rating: 4.9291449 out of 5
Keywords:
Id: LH75sJAR0hc
Channel Id: undefined
Length: 97min 39sec (5859 seconds)
Published: Thu Sep 29 2011
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.