{"id":5761,"date":"2018-01-07T18:55:29","date_gmt":"2018-01-07T18:55:29","guid":{"rendered":"http:\/\/putridparrot.com\/blog\/?p=5761"},"modified":"2018-01-07T18:55:29","modified_gmt":"2018-01-07T18:55:29","slug":"kotlin-language-basics","status":"publish","type":"post","link":"https:\/\/putridparrot.com\/blog\/kotlin-language-basics\/","title":{"rendered":"Kotlin language basics"},"content":{"rendered":"<p><strong>Hello World, again<\/strong><\/p>\n<p>The Kotlin HelloWorld.kt looks like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nfun main(args: Array&lt;String&gt;) {\r\n    println(&quot;Hello World&quot;)\r\n}\r\n<\/pre>\n<p>Which, it&#8217;s pretty self-explanatory. <\/p>\n<p><em>fun<\/em> declares a function which takes an argument named <em>args<\/em> of type <em>Array&lt;String&gt;<\/em>.<\/p>\n<p>Within Java we have the concept of packages and the same exist within Kotlin, the code above demonstrates that we do not require a package, but let&#8217;s add one anyway<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.putridparrot\r\n\r\nfun main(args: Array&lt;String&gt;) {\r\n    println(&quot;Hello World&quot;)\r\n}\r\n<\/pre>\n<p>For the JVM to correctly run the <em>main<\/em> method Kotlin automatically creates a wrapper around our code, we can write this manually like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.putridparrot\r\n\r\nobject Main {\r\n    @JvmStatic fun main(args: Array&lt;String&gt;) {\r\n        println(&quot;Hello World&quot;)\r\n    }\r\n}\r\n<\/pre>\n<p>Now this looks a little bit more like what you&#8217;re probably used to seeing in Java or C#. <\/p>\n<p>Kotlin doesn&#8217;t include a static method. If we require static methods, these should simply be created at the package level (like our original main function was). However in the above we use <em><a href=\"https:\/\/kotlinlang.org\/api\/latest\/jvm\/stdlib\/kotlin.jvm\/-jvm-static\/\" rel=\"noopener\" target=\"_blank\">@JvmStatic<\/a><\/em> to allow our code to be called by the JVM in the expected way.<\/p>\n<p>Oh, by the way, notice we do not require semi-colons to terminate a command, these are optional and more likely seen in situations where you have multiple statements on a single line (not that this is necessarily good practise!). <\/p>\n<p><strong>Importing packages<\/strong><\/p>\n<p>We can import packages using the <em>import<\/em> keyword, like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\n\/\/ import everything in the org.junit namespace\r\nimport org.junit.*\r\n\/\/ import a specific function\r\nimport kotlin.test.assertEquals\r\n\/\/ import the Test annotation and name it test\r\nimport org.junit.Test as test\r\n<\/pre>\n<p><strong>Classes &#038; Objects (basics)<\/strong><\/p>\n<p>We&#8217;ve seen that we can create functions at the package level and we can create an <em>object<\/em>. The <em>object<\/em> is more like a singleton or static class, but ofcourse we can also create non-static\/instance classes. <\/p>\n<p>Let&#8217;s look at creating a simple OO example using classes.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nopen class Animal {\r\n    open val name : String\r\n        get() = &quot;&quot;\r\n}\r\n\r\nclass Dog : Animal() {\r\n    override val name : String\r\n        get() = &quot;Dog&quot;\r\n}\r\n<\/pre>\n<p>There&#8217;s a few things to take in from this. First off, without the <em>open<\/em> keyword a class or method is final (or sealed) and hence cannot be overridden or inherited from. The <em>class<\/em> keyword declares our new type (pretty standard stuff). The Animal contains no constructor but we can assume it really contains a default constructor which takes no arguments. When we derive Dog from Animal, we need to in essence show the constructor that is to be called (i.e. the primary or secondary constructors &#8211; we&#8217;ll cover these another time).<\/p>\n<p>Kotlin includes the concept of properties, so in this case Animal declares a property name or type String which has a getter but no setter. Again it&#8217;s open so that we can override this in the Dog class.<\/p>\n<p>Finally, to create an instance of a class we do not need the likes of a <em>new<\/em> keyword. We simply write<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nval dog = Dog()\r\n<\/pre>\n<p><strong>Back to basics<\/strong><\/p>\n<p>As I had wanted to cover how Hello World was able to actually run and I&#8217;ve somewhat jumped ahead by describing the basics of OO within Kotlin, totally bypassing the real basics of a programming languages such as variables, assignment etc. So let&#8217;s return to the basics and look at variables.<\/p>\n<p><strong>Variables (val &#038; var)<\/strong><\/p>\n<p>As you saw in the last bit of code, we created a <em>val<\/em> named dog. Like F#, <em>val<\/em> is used to create an immutable value whilst <em>var<\/em> is the mutable equivalent. Hence<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nval a = 123\r\na = 456\r\n<\/pre>\n<p>will fail to compile due to <em>a<\/em> being immutable, thus changing <em>val<\/em> to <em>var<\/em> will allow us to mutate state. <\/p>\n<p>Notice that we did not declare the type of the variable, this was inferred, but we can include hints like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nval a : Int = 123\r\n<\/pre>\n<p>although in this example, the hint is superfluous as it&#8217;s quite obvious what the expected type should be. Had the intention been to store a float (for example) then we&#8217;d just change to this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nval a = 123.0F\r\n<\/pre>\n<p>Ofcourse we have all the expected\/required operators for use on a <em>var<\/em> include increment <em>++<\/em> etc.<\/p>\n<p><strong>Functions<\/strong><\/p>\n<p>We&#8217;ve already seen that to declare a function we use the <em>fun<\/em> keyword, so let&#8217;s create my usual Calculator example class and start adding some functions<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass Calculator {\r\n    fun add(a : Int, b : Int): Int {\r\n        return a + b\r\n    }\r\n}\r\n<\/pre>\n<p>It&#8217;s all fairly obvious, although we need to explicitly declare the types on inputs and outputs in a similar way to how we declare type hints. Like F#, Kotlin uses the <em>Unit<\/em> keyword for functions which do not return a value, although this can be omitted, hence these two functions are really the same<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nfun output1(a : Int) {\r\n   println(a)\r\n}\r\n\r\nfun output2(a : Int) : Unit {\r\n   println(a)\r\n}\r\n<\/pre>\n<p>Kotlin also supports expressions, hence we could write the above like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nfun output3(a : Int) = println(a)\r\n<\/pre>\n<p><strong>Comments<\/strong><\/p>\n<p>In terms of commenting code, simply think Java (C#, C etc.). A single like comment prefixes the comment with \/\/ and a comment block uses \/* *\/.<\/p>\n<p>Kotlin also include <a href=\"https:\/\/kotlinlang.org\/docs\/reference\/kotlin-doc.html\" rel=\"noopener\" target=\"_blank\">documenting comments<\/a> using \/**  *\/ blocks with the appropriate syntax\/labels. <\/p>\n<p><strong>Generics<\/strong><\/p>\n<p>As we&#8217;ve already seem within our Hello World main method, Kotlin supports generics (as you&#8217;d expect as it&#8217;s a JVM based language). <\/p>\n<p>Here&#8217;s a quick and dirty sample, which is pretty much as you&#8217;d expect if you&#8217;ve used generics in C# or Java.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass MyList&lt;T&gt; {\r\n    val list = ArrayList&lt;T&gt;()\r\n\r\n    fun put(item : T) {\r\n        list.add(item)\r\n    }\r\n}\r\n<\/pre>\n<p><strong>Classes, Objects &#038; Interfaces<\/strong><\/p>\n<p>Let&#8217;s return to the OO world of classes. Kotlin includes classes and interfaces. Unlike C#, interfaces can contain both non-implemented and implemented methods. i.e. for a C# developer these are more like abstract classes. For a Java dev (from my understanding) these are much like Java 8 interfaces (as you&#8217;d expect from a JVM bytecode language).<\/p>\n<p>Let&#8217;s look at our Animal and Dog derived class now using an interface<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\ninterface Animal {\r\n    val name : String\r\n        get() = &quot;&quot;\r\n}\r\n\r\nclass Dog : Animal {\r\n    override val name : String\r\n        get() = &quot;Dog&quot;\r\n}\r\n<\/pre>\n<p>The main differences from the previous example of this derivation is that an interface is <em>open<\/em> by default, hence we can override without the base class requiring the <em>open<\/em> keyword. Also interfaces cannot have constructors, hence no need to explicitly show that in the Dog class.<\/p>\n<p>We can multiply inherit from interfaces but not classes. Only one class can be derived from.  <\/p>\n<p>All classes derive ultimately from <em><a href=\"https:\/\/kotlinlang.org\/api\/latest\/jvm\/stdlib\/kotlin\/-any\/\" rel=\"noopener\" target=\"_blank\">Any<\/a><\/em> and <em>Any<\/em> can be passed as a variable in the was we might use <em>Object<\/em> within another language.<\/p>\n<p>Classes can take primary and secondary constructors, here&#8217;s how we create a primary constructor<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nclass HttpClient(url : String) {\r\n    val _url = url\r\n}\r\n<\/pre>\n<p>We can also declare a class without a primary constructor syntax, like this, using the <em>constructor<\/em> keyword<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nclass HttpClient {\r\n    var _url = &quot;&quot;\r\n    var _method = &quot;&quot;\r\n\r\n    constructor(url: String, method: String) {\r\n        _url = url\r\n        _method = method\r\n    }\r\n}\r\n<\/pre>\n<p>If our class already has a primary constructor, then any other constructors are classes as secondary constructors and will need to call the primary constructor using the <em>this<\/em> keyword<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\n\r\nclass HttpClient(url : String) {\r\n    var _url = url\r\n    var _method = &quot;&quot;\r\n    \r\n    constructor(url: String, method: String) : this(url) {\r\n        _url = url\r\n        _method = method\r\n    }\r\n}\r\n<\/pre>\n<p>We can nest classes, i.e. have inner classes, but Kotlin also has the concept of <em>companion<\/em> objects which act like friend classes within C++, in that they can access private members of the outer class &#8211; let&#8217;s take a look first at a simple nested class<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass A {\r\n    class B {\r\n        fun doSomething() {\r\n        }\r\n    }\r\n}\r\n<\/pre>\n<p>pretty standard stuff, now let&#8217;s see what a companion object looks like<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nclass HttpClient {\r\n    private var _url = &quot;&quot;\r\n\r\n    companion object Factory {\r\n        fun create() : HttpClient {\r\n            val a = HttpClient()\r\n            a._url = &quot;abc&quot;\r\n            return a\r\n        }\r\n    }\r\n\r\n    val url : String\r\n          get() = _url\r\n}\r\n\r\n\/\/ we can call this as follows\r\nval a = HttpClient.Factory.create()\r\n<\/pre>\n<p>So far we&#8217;ve used default visibility which is public, but we can use <a href=\"https:\/\/kotlinlang.org\/docs\/reference\/visibility-modifiers.html\" rel=\"noopener\" target=\"_blank\">visibility modifiers<\/a> such as <em>private<\/em>, <em>internal<\/em>, <em>protected<\/em> and explicitly set to <em>public<\/em>.<\/p>\n<p><strong>Lamba&#8217;s<\/strong><\/p>\n<p>Kotlin includes lots of the goodies from most modern languages, including lambda&#8217;s. Here&#8217;s an example of a method that takes a lamba<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nfun output(p : (String) -&gt; Unit) {\r\n   p(&quot;Hello World&quot;)\r\n}\r\n\r\n\/\/ and in use\r\noutput(::println)\r\n<\/pre>\n<p>Notice we declare the parameter of output (with name <em>p<\/em>) as taking a String and returning Unit. To pass a function to the lambda we prefix it with :: or we could pass as an anonymous function like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\noutput({s -&gt; println(s)})\r\n<\/pre>\n<p><strong>Extension methods<\/strong><\/p>\n<p>Let C#, Kotlin supports extension methods as a way to extend class functionality without inheriting or altering the class&#8217; code. For example<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nfun Animal.output() {\r\n    println(this.name)\r\n}\r\n<\/pre>\n<p>We prefix the function name with the class we&#8217;re extending (followed by a dot). So the above is obviously extending an Animal class (or subclass) and it&#8217;s implicitly got a <em>this<\/em> reference to the caller, i.e. if we called it like this<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\nval d = Dog()\r\nd.output()\r\n<\/pre>\n<p>then the <em>this<\/em> within the extension method is a reference to the Dog <em>d<\/em>.<\/p>\n<p><strong>References<\/strong><\/p>\n<p>This is just an overview of the basics of Kotlin, to be get us started. Check out <a href=\"https:\/\/kotlinlang.org\/docs\/reference\/\" rel=\"noopener\" target=\"_blank\">Kotlin Reference<\/a> for more in depth discussion of the topics.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello World, again The Kotlin HelloWorld.kt looks like this fun main(args: Array&lt;String&gt;) { println(&quot;Hello World&quot;) } Which, it&#8217;s pretty self-explanatory. fun declares a function which takes an argument named args of type Array&lt;String&gt;. Within Java we have the concept of packages and the same exist within Kotlin, the code above demonstrates that we do not [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[196],"tags":[],"class_list":["post-5761","post","type-post","status-publish","format-standard","hentry","category-kotlin"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"","_links":{"self":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5761","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/comments?post=5761"}],"version-history":[{"count":18,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5761\/revisions"}],"predecessor-version":[{"id":5808,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/posts\/5761\/revisions\/5808"}],"wp:attachment":[{"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/media?parent=5761"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/categories?post=5761"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/putridparrot.com\/blog\/wp-json\/wp\/v2\/tags?post=5761"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}