Advancing Android Development with the Kotlin Language


alright everyone, welcome! we are going to be talking about using
the Kotlin language for advancing development on Android, advancing how we
develop apps. So to start with we need to figure out why do we actually need to
move Android development forward, like what why do we need something that’s
advancing development. A classical reason that a lot of people make is that we’re
stuck in this Java 6 -ish, almost Java 7 it’s been called a wasteland. So we have
javax.time, is a library that came in Java HSR 310 and so we don’t have
this on Android we’re stuck with the old Date API and Calendar API which are
fraught with problems. There is no streams another Java 8 feature. The language
features, so lamdas, method references and anonymous classes that don’t capture
the outer a reference to the outer class and then finally try-with-resources and
so try-with-resources actually in Java 7 and Android went to almost jealous of him in
Apr 19 a little bit more in 20 but not all the way so only if you have a
minimum SDK can use that but as it turns out even though these four things are
are really painful, these aren’t true. So for javax.time there’s the guy that
wrote the majority of the code for Java 8 for the JDK actually back ported
the library to Java 6 and you so you can use that you can bundle that in your app.
For streams there’s also a back for it that takes it back to Java 6 or a
popular Java library RxJava basically implements the same concept in slightly
different and arguably more powerful way there’s a tool called RetroLambda, which actually take Java 8 bytecode and back port the lambdas and method references back to
Java 6 and like I said try-with-resources if your
main SDK is 1.9 but Retrolambda actually will also take try-with-resources and back port it to work on Java 6 So these these arguments that people
make about Java 6 being a problem there are there are tools for that I mean
granted it would be nice if we could just get out of the box but these
workarounds are are fairly well battle-tested and certainly are
available and work so that one doesn’t really count but there’s two that I I
really want to focus on which can’t be fixed in the same way and just
restrictions in the Java language in the problems that are present so we have
this inability to add methods two types to classes or interfaces that we didn’t
write ourselves that don’t exist inside our project traditionally these windup
in you tell classes just littered all over your codebase or slam together and
one you tell package and so while this is a solution it’s certainly not ideal
the type system in Java and especially in using an Android has problems with
null it has no first class representation of types that may be
known or may not be null and so oftentimes the so-called billion dollar
mistake of the null pointer exception ends up killing your out and then just
you know Java is certainly not the most terse language and that’s not
necessarily a bad thing but there’s a lot of common idioms that just end up
being overly verbose which can potentially lead to errors and bugs in
your code that’s the job on problems with the Java language itself and there
is also the Android API that we have to deal with Android is big inheritance
party they love their inheritance which works well for them but it tends to push
problems on us as application developers the nobility problem comes back and this is especially apparent in
Android where things they they want things to be efficient sonal is used in
a lot of places to represent the absence of value instead of something that would
rapid and more high-level high-level type which you know kind of either type
or optional and then again back to the verbosity Android itself its API’s have
a lot of ceremony in this also goes back to you just wanting to have high
performance is that the end up writing these API’s that require you the
developer to do a lot of things in order to provide efficiency instead of
abstracting it all away so Java and Java language and the Android API eyes are
really the two motivating factors for why something like a language like colin
could be appealing and it’s not to say that the job a sixth is a problem
because collin addresses a lot of that stuff but I don’t think it’s a good
enough argument to me because of those alternate tools so if you don’t know
colin colin is a language by the company JetBrains developers of IE’s four tons
of different languages the intelligent platform which is the
basis for Android studio and so this this is there a little website
statically typed language for JVM Android and actually the browser as well
so it will compile 22 JavaScript although that focus has been pushed back
to be armed version 1.0 but it’s really targeting the JVM and Android and Java 6
play codes they want to add these new features in a language while still
supporting these these markets of the job of six and up JVM and obviously and rude and they
focus heavily on job us will see that a little bit later on alright I am NOT going to cover a ton of
like introductory introduction that collin the language in the syntax itself
the the website and the tutorials are really great for going through this but
I didn’t want to kind of just jump into why the language is good for Android
without going through some some syntax that will see and I’m not gonna cover
everything there will be points throughout the rest of the talk about
introducing new syntactical elements to start with this is what a a method like
we have a fun declaration which transfer function with the name of the method and
the first thing to note that’s significantly different than Java is
that the order of the argument name and the argument type is reversed so the
type comes after the name the return type specified on the end of the method
and actually this because I so there’s no semicolon so you’ll see the return
does not have a semicolon after it and what’s also interesting is that because
this is a single expression function the function body only has one expression
inside of it we can actually get rid of the the curly braces and the return and
actually just make the method equivalent to the expression will see this
shortened syntax comes in really handy later on is another example of this
would be what the main method looks like your writing just a normal job
application we see that there’s no there’s the array syntax for a type of a
little bit different and it’s treated more like a generic the biko that gets
admitted will use a string array but in your code you get to treat it like it’s
just generic and then why we’re not going to touch on this pretty much
anywhere in the rest of the taqueria string interpolation so we can write
strings and reference variables inside of them and how be automatically replace and finally
just a look at some some variables so here I am assigning a string to a
variable called name and there’s no type here it’s actually going to infer that
site because it can only be a strength and you’ll see that I is prefixed with
Val Val is a value which is an immutable type it can be changed wear something that was beautiful and we
wanted to change it we would use fire for variable so here’s what I look like
on a field comes after the name just like in a method and then finally when
we call constructors we actually don’t have to use the new keyword exact same
syntax for the rest of it but just dropping the new ok let’s move on into
the features of the language and how they’re going to help us in building our
Android apps so I pointed out that these you tell classes are not necessarily a
problem but they’re almost kind of an anti pattern and they end up growing out
of control in your application for colin has this concept called extension
function and it’s not unique to the color language but it ends up working
out in a slightly different way than we see in other languages so we wanted to
add a method today in just pure Java we would write a date utils class or dates
class and put a static method on it and that just takes in an instance and does
something potentially returning about it so here I am adding the ever useful is
Tuesday method to your details and then we were just call it as you know a
traditional static method so before I show the columns into actually won a
contrast this with me Sharpe this is what an extension method will look like
in c-sharp on its version of the Day Class D time and so the interesting
thing here is that we we get our date instance you can call this method in
this actually works anywhere in your entire project and dotnet so as long as
there’s a extension method declared somewhere you can use that on any day
time in the entire project and explain why that’s interesting distinction in a
second here Scotland we prefix the method name with
the type that we want to add the method to so instead of just is Tuesday we’re
now date is Tuesday then you can see a return type at the end and we end up
calling get day and so this extension function is acting as if it was on the
type so we don’t have to we don’t have any instance to call we just call us if
we were already a method on class okay and then this is how we would call it so
now if we have a variable in that same same file our data objects for now have
an is Tuesday method did you call that like any other method on day one of the
nice language features of colin is that it actually automatically will confer
types that have getters and setters to have synthetic properties so I’m no
longer calling get day I’m referring to this day property which exists and so
this this doesn’t it kind of looks like a field that this was a public field but
it’s not this is a property in SA’s property is just the concept of a getter
and setter merged together and I pointed out earlier that its single expression
methods can be put into a mortar syntax we can actually just move that up into
the top and get rid of the return tape because it can be inferred and now we
have this nice little one line extension method that we can use on date now when
I said we’re calling this on a field in the same file that was something that’s
important and that’s why it’s different then C sharp so this is in the same file
this is going to work however if our extension method is to find you on some
date extensions class in our field there were using it on since a some activity is actually not
gonna work you will get like a message not found in Decatur be nice and read in
studio that’s because unlike csharp extension methods have to be explicitly
imported if they’re not in the same package so here we would have to be very
explicit about where this extension function is coming from and so this this
is very similar to how hard he works with its static method imports we have
to be very explicit about the method that were calling and this allows this
allows to be unambiguous about the source of that method because if I look
at this I know there’s no is Tuesday method on date as a Java developer but
the explicitness of the import tells me that it’s coming from you know this calm
example you till package whereas in c-sharp you have no idea where that
extension method is coming from maybe a library maybe in your source you have no
way of knowing statically without actually going into you know the IDE and
allowing it to figure it out and of course like you can come and be and step
into this method it behaves just like it was a method on the date type so let’s
see this basically is what the bike owners gonna look like when the column
compile Iran’s because obviously this this has to turn into Java code rate
like there’s no there’s no colin runtime it’s running on our devices on the JVM
it’s just running on the normal biko interpreter so if you haven’t seen by
code this is the job equivalent of what that biker represents
a notice it is exactly the same thing as what we would have otherwise wrote if we
only we’re doing Joba it’s the same static method an interesting thing is
that if I i mentioned that Colin wants to interrupt with Java it understands
that you you know your entire project him because code so this actually is
gonna wind up getting generated in a class called dat extensions Katie . job
and that’s because the class that we’ve defined it is called dat extensions and so if we were interacting with you
know existing Java code we want to present this as if it was something
raining Colin you shouldn’t know that you’re calling into colin has a handy
indication that you can put on the file which allows you to control the
generated name so in this case we want to turn it into day you still so that it
looks like our old details class of course you don’t have to you know
continue with the utils naming convention you can use whatever you want
the point is that you can you have the ability to control it and also just
remember that this details that Java class doesn’t the class exists but the
source file doesn’t exist so this is just a representation of the class file
that gets generated number to speed up the rest of my talk one thing that you
can’t do you cannot override existing methods of a class has a good day class
has get day we can actually override existing method that would create some
ambiguity but it’s actually slightly unfortunate because this would be a
fantastic way to retrofit API’s that are on newer versions of
Android to older versions of Android we could conditionally call into the real
method if it was available or fall back to you a compatibility version if we’re
on an older version of Android that’ll work see you you could do something like
a compact version directly on the class that you want to do instead of having to
do like you can patent that’s a really good use for extension functions is
taking existing API and fixing what’s broken so text to you has these two
awful methods and you’re almost always going to call them incorrectly the first
one doesn’t really specify what units and the second one has its printers out
of order doesn’t really make sense to say I want to set the text size to Pixel
6 tricia lee you put the the Union after the size and so this is a great way that
we can just slap a new method on to text you that’s much more semantically
correct the Texas size and we can actually enforce you know some kind of dare I say to use
the units and then that can have behavior which converts it into pixels
the value into pixels and we just call into the normal set excise method and so
it is impossible to call this method incorrectly because you have that the
number which can only be a phone and represent what size it is and you have
the genome which stands for the hour what unit the number is actually
representing and it takes care of converting it to pictures itself another
example is a cursor cursor is one of these classes that’s really optimized
for its API’s are optimized for being efficient not exactly for being useful
so in order to get a string for a column out of a cursory have to make two method
calls that we have to get the index of the column that we want and then get the
string at that index and so if this actually if this column is knowable we
have to do a lot more than that because we have to get the column index them
have to check if that index is now and then we can conditionally get out the
strength this is terrible codes to have to write every time you wanna get
something out of a cursor sure you could rapidly and you know our static that
accuse all method but that’s exactly what these extension functions are four
so we could add two methods to the cursor type which is going to take care
of doing this dance for us where are you now have to do is pass in the column and
it will take care of doing the conditional reversal looking up the
index so interesting thing here up interesting thing to note here that
haven’t covered I talked about no ability being a problem culling actually
represents no in its type system so for the get stronger no method and returning
a string question mark to indicate that this might return a null value and then
down in the get string method I’m just calling the Arenal and using this double
exclamation mark syntax and this is basically just saying I know this is not
going to be no so turn it into just a normal string and so this will actually emit a check
where it is if it is not only will throw an exception but in the consuming code
the code that’s calling this method the type will be a string question mark that
will be propagated you for calling the first method will be propagated down to
the calling code and that means that you can never dereference that field without
first doing a no check or providing a default so it made it virtually
eliminates the fact that the ability for this to cause an open-air exception in
the code that consuming it right the next concept car look at is called
function expressions and elsewhere these are known as just lame ducks or maybe
closures so here’s an example of the simplest version of function expression
it’s basically just a a block of code that is calling the toString method on
this it variable and so it is actually a a
built-in name when you’re writing this function expressions if there’s only one
argument being passed into this block of code you can refer to it as it and it’s
just a way to not have to define arguments but if we do need to define
arguments or there’s more than just one this will be the syntax for doing that
so we can create a piece of code a function expression which takes into
pieces of data and add them together if we want we can specify explicit types
for this second entry there we can only do that if the types were somehow
inferred from some other context but if we need to declare explicit types we
would do the same place again after the argument name and then like to store
these in fields so now you can see that the first or the second example rather
the type is declared on the field itself which means that the function expression
doesn’t need to include any type information and then down at the bottom
the type information is included in the function expression itself so we don’t
need to included in the variable declaration and also in the last one the
return type is inferred so it knows that two integers are going
in and it knows that it’s adding them together and the only thing that can
come out is an integer so you don’t have to be explicit about it just examples
like how these are useful we’re gonna look at these a lot more I just need to
introduce the concept first so we wanted like validate data that’s coming in we
could check if you no strings on empty you if its length is greater than 4
eccentrics to hear storing them as fields and the idea here is that sucks
of code now become data are you can move around so I can declare this piece of
data this data that operates on a string and does validation and I can have it in
a field or variable and then move that around to the place where it’s needed
we’ll see where this comes in handy later alright so the next thing is
higher order functions and this is just a really fancy term for functions that
except the function or functions that return function as an example so we
define a function which is going to take in two integers and then as its third
argument is actually going to take in a function so that that’s the same syntax
as we saw in the previous slide forward to finding a function that takes two
integers and returns an integer and then inside the method body it’s just going
to call that function with the two parameters so here’s how I would use it
to create a some we’re applying this block of code onto these two numbers and
we can also use that to you get a difference we apply a different block of
code to those two numbers and again this goes back to the point where we’re
taking this disco disco that knows how to have this code that knows how to
subtract and we’re turning that into data that we can pass into this apply
method and then it can take care of running it when it has the appropriate
context to run it and Colin actually gives you a handy way
of turning this into the slightly nicer syntax whereas if the last argument of a
method is an expression you don’t have to have the parenthesis all the way at
the end you can just have it after all the initial arguments so the pregnancies
at the end here we actually just slide over before the function expression and
at the function expression at the end and it still calling that same method
but now we’ve made it the syntax row little more nice to see that this
technique is going two hours to create really nice DSL and API’s later on okay
so rain on taking into integers is higher and higher function could also be
just an extension method so instead of taking into integers I’m now making an
extension method on an integer and that would change the Conchords look like
this are integers now have methods that we can apply some behavior to another
integer the syntax is gonna come in useful later
on the examples are kind of weird the ones at the annual really resonate and
so you also don’t have to take in any just normal arguments you can only taken
the function expression and it’s nice here is you don’t even have to specify
parentheses at all so now we’re applying some block of code onto a number also
really weird example but you’ll see later that this sin taxes now going to
create something very powerful and again if there’s only one piece of data being
passed to the function expression we can just refer to it as it right so let’s
take a look at some more practical applications of how this would work common operation is just having a list
of things and needing to filter it based on some condition so now we can because
we have extension methods because we have higher functions we can we can
write this weekend raid a method on list that does this for us and we will do it
in the normal way so we can look at just a syntax here so it’s just an extension
method and its taking in an expression which uses the generic type and returns
a boolean so we’ll just call this for every item in the list and then returned
a new list that only has the items that return true it’s exactly the same as you
would do if you were doing this manually create a new list over the items in the
last week also function or some online if they men and then just if it returns
true then you add the method are you at the instance to the newest the end up
returning it and so now we have some list of data in one line of code in this
nice first little function we can now filter it the only pull out the things
that we need thankfully this function is actually built into the cotton standard
library so we don’t have to have to extend list a large majority of the
standard library of colin is just augmenting these Java types that already
exist with ease higher-level methods that provide
comment operations on them an example that doesn’t exist in the Collins Center
library we had a method instead of doing synchronize blocks we could use an
expression to execute code in in a synchronized block so many years Collins
version of object every type is a subtype of any and we can add a method
to it that just takes in a function and executed inside a block that
synchronized on that instance so we have some from walk that object that we need
to lock on we can put the code that executes inside that lock inside a
function and pass that to this method that’s on every instance and so it kind
of it cleans up the calling code makes it a little bit more clear and another
pretty cool application of this is that a common problem with doing blocking is
that oftentimes you’ll have code that forgets to do a lock before it does some
operation we can write a class that actually only allows you to access the
the type that you need to interact with if you have a lock on it so it’s
impossible in this case we’re working as JSON reader which is on some stream and
say we’re accessing it from multiple threads another I know why you would be
accessing Jason reader from multiple threads but this is going to prevent us
from accessing this instance unless we take this lock which is going to take
care of synchronizing for us later on in the code we call this acquire method and
it’s going to synchronize on that instance and then tacit to the function
that we gave it and so this case I you know read a string from this Jason
reader and we can only do that if we have the lock and so now here we’re not
dealing with we’re not dealing with locks at all not doing with explicit
synchronization and having a lock and the JSON reader it’s impossible for us
to access that that Jason Reeder without taking the lock solving bugs preventing box before they even happen
earlier on I talked about the code as data and so here is our ears are cold
and so we could now with this higher functions we know how to use that so we
could have method on text you does the validation for us and we can pass these
functions into that method and allow it to do validation as you know someone’s
editing and a text an interesting thing to note is that the way that collin
implement these you know pieces of code in a function expression is the same way
that you would do it in Java using his classes and so what’s nice is that it’s
not actually you know normally you would you like validate with you create a new
anonymous class put your your data in there but that’s actually talked about
nine capturing anonymous classes that class that you create is gonna have a
reference to the outer class that’s a great way to like the context and that’s
not what we want to do but column when it when it creates this class because
there’s no reference to the outer scope it all we care about is the data being
passed in its gonna create a singleton instance that as a static and has no
reference to the incident at all so it’s basically it’s now impossible to legal
context with these function expressions but at the very top here we have two
that are the same it’s actually not smart enough and it could be argued as
not even being correct to duplicate so even though they’re exactly the same
pieces of code they’re gonna turn into two generated classes each of which have
their own instance if you wanted to eliminate that you just have to
duplicate it yourself stored in a field first store in a very
morn antacid ok so this is where we’ve been getting to talk about extension
functions were adding methods two types and allowing them to behave like those
methods were always there that their natural to that type we talked about
representing code as data just these function expressions that we can pass
into methods and then the higher functions which is a fancy name for a
function that takes a function so extension function expressions are the
combination of all three of these concepts into a really powerful way to
make clean abs and so to demonstrate that I’m going to take an API that we’re
back to Davis is my take the CPI and turn into something much more terrorists
and prevent us from writing invalid code so these are the six lines of code that
you have to rate if you wanted to execute a statement in a transaction
start the transaction we put in a try finally we execute code and we have to
mark the transaction is successful and if that throws or it doesn’t throw in
the finally block we have to end the transaction this is the type of code that’s that’s
prone to bugs to forget for mastery factors anything could go wrong here
where you actually spoke to things and all the sudden you have a very subtle
bug that’s hard to catch or maybe just blows up all the time at runtime extension function expressions are going
to allow us to fix that we can now add a method to the database itself which is
going to encapsulate the boilerplate of that chunk of code the starting the
transaction the doing the try block and setting the transaction successful and
finally ending it and so we take in a function and we run that function inside
after inside the try block after we’ve done that little dance and now and are
consuming code we just have this method that we call in transaction on and
anything we put inside that is going to execute a transaction with there’s no
way for you to screw this up almost no way interesting thing here is the way
that we’ve implemented this you still have the reference the database inside
the piece of code and so that could potentially be something that you mess
up if you have two databases may be referenced the wrong line inside a
transaction for the other one and so we have ways to fix this one we
could do as we can actually taken a function whose arguments take send the
database that the transaction as I am now instead of calling GB so we have to
pass in this into the function and now instead of congee be we can just use
that that it that first argument that’s passed to the expression so this is
still kind of annoying we’ve potentially prevented a bug but it’s still annoying
to have to specify it every single time you want to access this database and so
it’s interesting here is that the argument that’s coming in is a function
and we can change that function to actually itself be an extension function
on satellite data base and so this this gonna blow your mind but it’s it’s
actually a crazy powerful concept so the function that’s being passed in is now
an extension function on that object and so instead of passing in this into the
function that function actually exists on the seagull a database now so because
we don’t really need this will just get rid of it but the function behaves as if
it was defined on sequel I did it and what’s great is that if we want to call
this delete method we don’t have to qualify it with anything because we are
a sequel a database we cannot get rid of that it it’s not every expression that
you put inside this this block is going to behave as if it was like a private
method inside single a database so you’ll have to qualify it with anything
you will always execute on the right object and this is fantastic that’s
where we turn our code into but there’s still problems still huge problem
actually for Android and that’s the generated code looks like this which is
crazy but it’s not that bad only five or six lines but the
equivalent in Java code is actually creating a new instance of a function
and passing it into are generated static method and this is kind of unfortunate
because before we just had a bunch of lines of code they’re executing in order
not really doing any allocation and if we do this we have to allocate
these tiny little function objects every single time we want to use these
extension function expressions this is this is not good is gonna create these
are the types of objects that just end up causing a lot of G Series tiny little
objects thankfully there’s a way to get rid of it on our function that we have
here we just defined as an extension function and it takes in this you know
extended this function expression and that’s the problem is that that function
expression has to turn into an anonymous class we can actually take this and
turning into an inline function we can tell the cotton compiler that what I’m
doing inside this method I need it’s actually instead of just calling it as a
static method I need to actually take my body and replace it in the calling code
and so that generates all this nonsense but that’s great because that this is
the job equivalent and at the same exact slide that we started with so the
generated class file ends up looking exact same as if we were compiling this
potentially Arab problem Java code exactly the same so rule of thumb
extension function expressions frozen inline function equals the exact same
equipment as the Java code and so now we can clean up any API that we want you
know pick pick your worst API Android there’s certainly no shortage there’s a
lot that a transaction-based so we could reuse the same pattern for fragments are
for shared preferences or just anything like that annoys you and you feel like
your writing too much code so I just picked a random notification builders
you end up there are not too bad but we can like clean up a tiny bit and so just
finds an API that that has a lot of this was actually doesn’t have a lot of
ceremony but there are a lot of API’s are you just have to do certain
operations in order or you have to remember to put that inside the try
block or outside the try block or not a synchronized block were you know there’s
tons of these examples and so this is a great way to add functionality to these types with no
overhead in the actual generated code and so we’ve all kind of had taken us to
a ridiculous extreme creditors library card and go and it’s really clever it
it’s basically the idea that declarative and it’s actually perfect
for you I because its hierarchical and you eyes are inherently hierarchical
when you’re building them up but with these extension function expressions we
can now represent that in code in that same hierarchical way while still having
the ability to reference all of the methods and all of the reflector and
tools and all this static analysis of Java code itself for representing you
eyes and so these are just a bunch of extension function expressions which are
going to generate you know call create instances of these classes at them to
their parents at the right properties and instead of the concepts that we
using XML like including layouts you can actually just call a function call a
method that returns this partial layout and composes things together so it’s
it’s certainly an interesting concept it’s safe enough for everyone they also
have a custom preview plugin so one of the nice things about XML you get 23
render the view and see how it mostly luck on a device and so they’ve written
one for this java code so well statically parse the Colin and do that
rendering as well so it’s a great example of taking something that annoyed
them which is the XML and the general pain of working of having these two separate worlds of
Java and XML and resources and combine them into a single single source which
is just the cotton source file and so this was actually end up faster than XML
because you eliminate the overhead of parsing XML and you eliminate the
reflection that incurred when you look up the classes that are defined in XML
so it’s not for everyone but it’s it’s simply a novel novel solution to a problem that they
perceived and so that’s it I really just wanted to give a kind of an introduction
to the concepts that are most useful for fixing the problems of Android there’s a
ton of other things in the common language that are just general
improvements but that’s that’s for any Java code and there’s these very
specific things which allow you to take the problems of Android and potentially
remedy them so that the the column website is absolutely fantastic here
there’s a there’s a ton of resources as a interactive editor actually create and
run cutting coaches in your browser and have a series of interactive tutorials
that you can step through that will teach you the syntax in that same editor
and so yeah that’s all I have I just want to point out that colin is just hit
its first beta 2 days ago I think so the final one doe language is about to be
released here and hopefully a few weeks targeting by the end of the year so a
lot of people have been holding off because it’s a pre 1900 language so that
argument for not using it is about to disappear like you altered to go out and
experiment with it and thanks for coming

Leave a Reply

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