A roundup of Swift/Kotlin comparisons

by Joey deVilla on May 23, 2017

Spock and “Mirror Universe” Spock. (And yes, that’s the Kelvin Timeline Spock,
not the Prime Timeline Spock.)

With the recent announcement that Kotlin has become an official Android development language, it’s a good time to do some comparisons between Kotlin and Swift. I rounded up some interesting ones so you don’t have to go looking for them. Enjoy!

Swift is like Kotlin!

Swift is Like Kotlin is a side-by-side comparison of those parts of Swift and Kotlin that make them seem as if they’re dialects of the same parent language.

…or maybe it isn’t!

If you don’t read Japanese, you’ll need to run Swift is NOT like Kotlin through a translator (Chrome will automatically offer to do so), but it’s worth doing. The article highlights three features where the languages first appear similar, but upon closer inspection are rather different:

  1. Protocols and extensions
  2. enums
  3. Properties

Anything you can do, I can do better

Anything you can do, I can do better is a presentation at UIKonf 2017 by two engineers at Kickstarter — an Android engineer who got into iOS development, and an iOS engineer who got into Android development — where they talk about how they develop for Android and iOS using functional programming, Swift, and Kotlin. A good chunk of the presentation is devoted to a tour of Kotlin “all its similarities, strengths, and weaknesses with respect to Swift”.

If you want to dive really deeply into what they’re talking about, they point to the GitHub repos for Kickstarter’s open source iOS and Android apps:

SwiftKotlin: A Swift-to-Kotlin translation tool

SwiftKotlin is a framework/command line tool/Mac application that applies transformations to Swift code to convert it into Kotlin. According to its README on GitHub:

It applies transformations to the Swift code to get as correct as possible Kotlin code (see limitations below). It does string transformations as well as some more complicated ones like transforming guard statements to negative if statements, properties, memory management and many others.

Swift vs. Kotlin for real iOS/Android apps

Here’s a comparison of Swift and Kotlin that starts with a laundry list of differences, followed by a simple app that consumes OpenTable’s API implemented in both Swift and Kotlin.

“Swift and Kotlin” presentation

Here’s a presentation that does a side-by-side comparison of Swift and Kotlin.

Uncle Bob on Swift and Kotlin’s “Dark Path”

An actual still from one of Uncle Bob’s “Clean Coder” videos, in which his Starfleet self talks to his mirror universe self.

Robert C. “Uncle Bob” Martin is the “Clean Code” guy and one of the attendees of the Hot Tub Time Machine-like ski gathering in 2001 that gave rise to the Agile Manifesto. In a recent blog post titled The Dark Path, he wrote:

Over the last few months I’ve dabbled in two new languages. Swift and Kotlin. These two languages have a number of similarities. Indeed, the similarities are so stark that I wonder if this isn’t a new trend in our language churn. If so, it is a dark path.

Swift constructs for Kotlin

Here’s a quick article that shows you how to implement Kotlin versions of some Swift goodies that you may have become used to.

Kotlin, Swiftly

Episode 257 of the podcast Coder Radio spends a fair bit of time on Kotlin, including its similarity to Swift.

Will Swift and Kotlin change the face of mobile development?

You can read this entire article, or just the final paragraph:

While it’s unlikely that we’ll reach the point of just using one of these languages to code for both mobile platforms anytime soon, their similarity, and the fact that their adoption is moving outside of just the mobile arena, will impact our mobile teams. More robust products built from closer developer collaboration, consolidated and streamlined support teams, and the ability to keep developers engaged by allowing them to more easily work as full stack developers, are some of the ways future mobile teams will be different from those of today.

{ 1 comment }

I’ll admit it: I cheered when Steph Saad Cuthbertson, Android Project Management Director (and Program Manager for Visual Studio during my time with The Empire), announced that Kotlin is now a first-class Android development language. This is fantastic news, especially for people like me, who wince every time they have to switch from iOS development in Swift to Android development in Java.

jetbrainsKotlin is the creation of JetBrains, who have released a number of nice development tools over the years. Many of you from the .NET world live and die by ReSharper, the add-on that supercharges Visual Studio and takes a lot of drudgery and donkey-work out of .NET development. If you’re a Java developer tired of the nightmare of self-flagellation that is Eclipse, you probably use IntelliJ IDEA. And if you’re building Android apps, you probably are still giving thanks for Android Studio, which was built on IntelliJ, and has spared you the horrors of Eclipse.

kotlinSix years ago, JetBrains embarked on a project to build a new programming language named Kotlin (whose namesake is an island near St. Petersburg, Russia, where one of their development teams is based). It borrows from Scala, has a number of notable similarities to Swift, and is — in my personal opinion — so much nicer to work with than Java. It’s also seen real-world heavy-duty actual-software-in-production use not just by JetBrains for building their own products, but in Flipboard, Pinterest, Square, and Expedia.

If you’re feeling iffy about trying out Kotlin, you don’t have to dive in all at once. Kotlin integrates seamlessly with Java and vice versa — you can call Kotlin code from Java and Java code from Kotlin. You can start by adding a single Kotlin class to a Java project and work from there.

But if you’re like most of this blog’s readers, you’re not feeling iffy about trying out Kotlin. This article is for you! In it, I’ll walk you through building an incredibly simple Kotlin app to give you a small taste of the Kotlin language and developer experience: Oblique Strategies.

What is Oblique Strategies?

Oblique Strategies is a “press a button and get a random response” app based on Brian Eno (as in the avant-garde musician and producer) and Peter Schmidt’s (the visual artist) creativity tool.

Eno and Schmidt created Oblique Strategies in late 1974 as a tool to help artists, writers, musicians, and other creative types overcome creative blocks. The original version was a deck of cards, each with a constraint, question, or suggestion that encouraged what was then called “lateral thinking” and now called “thinking outside the box”. If you were feeling creatively blocked, you’d shuffle the deck and then draw one or more cards, each of which would say something such as:

  • Abandon one stricture.
  • Emphasize repetitions.
  • Is there something missing?
  • What would your closest friend do?
  • Use an old idea.

If you’d like to try out Oblique Strategies, there are a number of web versions: herehere, here, and here, for starters.

In this exercise, we’ll remake Oblique Strategies as an app. Here’s what the end result will look like:

(If you’re experiencing deja vu, it’s because I posted an article on building Oblique Strategies for iOS with Swift back in March.)

Creating a new Kotlin Android project

The shaving yak from Ren and Stimpy.

Before Android Studio 3.0, creating a new Kotlin-based Android project required a little yak-shaving to configure Android to work with the language. Now that it’s a first-class Android language, it’s not just a simple process — it’s the out-of-the-box default.

From here on in, you’re going to need Android Studio 3.0 (the latest version at the time of writing is Canary 1), which you can download here. It can coexist on the same machine as any 2.x version of Android studio.

Open Android Studio 3.0 and select File → New → New Project. You’ll see this:

Do the following:

  • Provide a name for the application in the Application name: text field. I chose My First Kotlin App, but you can name yours whatever you like.
  • Make a note of the fact that the Include Kotlin support checkbox is checked by default. We’ll cover the significance of this once we’re done creating the new project.
  • Click the Next button.

You’ll be taken to the next screen:

Click the Next button, which takes you this screen:

Make sure Empty Activity is selected, then click Next, which takes you to the final screen:

I went with the default activity name, MainActivity, but you can rename it if you like. Then click Finish. Android Studio will do some crunching, after which you’ll be taken to your newly-created Android project.

The significance of “Include Kotlin support” as the default option

Before we put together the app, allow me to make one side trip.

Let’s take a closer look at the code for the main activity:

Even though the main activity is contained within the java folder (which is where you’d expect to find it), its filename is MainActivity.kt (.kt being the Kotlin code filename extension) and its code is in Kotlin.

If you’re in the mood to experiment, go ahead and create a new project with the Include Kotlin support option unchecked. You don’t have to, but if you do, you’ll find that the main activity file is named MainActivity.java and that its code is in Java. You’ll also find even though you’d explicitly refused Kotlin support by not checking that box, File → New still gives you the option of adding a Kotlin file to the project. When you do that, Android Studio will drop this hint near the lower right-hand corner of its window…

…and if you follow the easy steps provided — a couple of clicks — it’ll make the necessary changes to build.gradle (Module: app) to add Kotlin support to your project.

If these tea leaves aren’t obvious enough, I’ll simply spell it out: The future of Android development is Kotlin.

This shouldn’t be surprising. First, there’s the legal incentive to move away from Java. Despite various rulings in Google’s favor, Oracle apparently won’t rest until they’ve made a cash cow out of Google over their use of Java. Oracles’s continual lawsuit filings against Google are a very strong incentive to move away from Java.

Then there’s the toolmaker. Both Kotlin and Android Studio are creations of JetBrains, who have become increasingly cosy with Google. There some great quid pro quo in this relationship: Google gives JetBrains, its tools, and Kotlin the kind of exposure that only Google can provide, and in exchange, JetBrains provides Google with fantastic tools, and a language that’s both great and a way out of the toxic Oracle/Java situation. As long as that strong JetBrains/Google symbiosis exists, so does the incentive to support Kotlin as the preferred Android development language.

And finally — and most importantly, in my opinion — there’s developer love. There’s lots of love for more easily-read, powerful modern languages like Rust, Swift, and Google’s own Go, as seen in the most recent Stack Overflow developer survey, and Kotlin is among them — developers love it.

However, it’s not enough for a programming language to simply be loved by developers. It also needs a killer app, and Android — which runs on 2 billion devices today — is Kotlin’s killer app. Just as Rails moved Ruby from from obscurity to TIOBE’s top 20 and iOS did the same for Swift, expect Android to take Kotlin from relative obscurity to the mainstream. In fact, I don’t think I’m going out on a limb by making the prediction: Kotlin will break into TIOBE’s top 20 sometime in 2018.

A little setup

Before we can start coding the app, we need to do a little setup. Don’t worry — there isn’t much setting up to do.

First, let’s define the user interface. Open the main activity layout file, activity_main.xml, in Text view and replace its contents with the XML shown below:

(Yes, I know I’m breaking a few Android rules by directly defining text and textSize values right in the activity layout instead of doing so in various values files, but I’m trying to keep the amount of setting up to a minimum so we can concentrate on Kotlin.)

Once you’ve pasted in the XML, you should be able to switch to the main activity’s Design view and it should look like this:

We’ll also need to provide the app with a set of strategies to select from at random and present to the user. We’ll do this by creating a string values resource file. In your project, expand the res folder, and then add a new values resource file by right-clicking on the values folder and selecting New → Values resource file:

You’ll be presented with the dialog box shown below:

Simply enter oblique_strategies into the File name: field and click OK. You’ll now be viewing the contents of a newly-created resource file named oblique_strategies.xml, and its contents should be:

Replace those contents with the following:

At this point, you now have:

  • A user interface for the app
  • A set of responses that the app will provide

The last bit of setup is adding the Kotlin Android Extensions plugin to the project. Open build.gradle (Module.app). You’ll see that it starts with these lines:

As may may have reasoned, the first line adds a plugin that makes it possible for Gradle to build Android applications, and the second line adds Kotlin language support. Before Kotlin became a fully-supported language in Android Studio, you had to add this plugin yourself and do some additional setup.

To add the Kotlin Android Extensions plugin, add one more line to the file so that the start of build.gradle (Module.app) looks like this:

You’ll see what this plugin does for you in the next section, titled Getting references to widgets.

Now that we’ve done our setup, it’s time to start coding!

Getting references to widgets

If you look at activity_main.xml, you’ll see that there are two widgets that account for all the interactivity in our app:

They are:

  • getStrategyButton, a Button that the user presses to get a randomly-selected strategy for overcoming a creative block, and
  • strategyTextView, a TextView that is used to display the randomly-selected strategy.

If this were a Java project, you’d need to write the following code in order to be able to programmatically refer to these widgets:

This is a Kotlin project, so it’s a little different, and rather than tell you how it’s different, let me show you. Go to the code for the main activity, MainActivity.kt. The body of the MainActivity class should look like this:

Let’s do a little experimenting. First, add some blank lines at the end of the onCreate method…

…and then in that space, start typing getStrategyButton. You’ll notice that even though you haven’t done the traditional findViewById dance, getStrategyButton is already defined:

Once you complete typing in getStrategyButton, you might notice that Android Studio has added an extra import statement at the top of the file:

Here’s what’s happening: the Kotlin Android Extensions plugin gives Kotlin activities a set of synthetic properties that let you access any widget by its id. You no longer need to use findViewById!

Lambdas in Kotlin

Now that Kotlin Android Extensions automatically gives you references to activity widgets, let’s do something with those widgets by having the app respond with You pressed the button! whenever the user presses the Get a strategy button. Update the onCreate method so that it looks like this:

Run the app, and click the Get a strategy button. You should see this:

Let’s take a closer look at the setOnClickListener method in Kotlin. Here’s its method signature:

Note the following:

  • Function declarations begin with the keyword fun.
  • Variable and parameter declarations use this format: variableName: type. In the case of setOnClickListener, it accepts a single parameter, l, whose type is (View) -> Unit, which specifies a function that accepts a View as its argument, and does not return a value (Unit is Kotlin’s equivalent of void).

With setOnClickListener’s method signature and these two points in mind, you’d think that we’d have used code that looked like this:

This is perfectly valid Kotlin syntax, but there are ways to streamline this code (which is already more streamlined than its Java counterpart). First, if the last argument is a function, it can go outside the parentheses:

If you code in Swift, this will be familiar to you, as it’s a commonly-used idiom in that language.

We can streamline the code further. If a function takes only one parameter, and that parameter is a function, you can skip the parentheses entirely:

We’re not done streamlining yet — since we’re not using the lambda’s parameter, we can omit its left side entirely:

Goodbye getters and setters, hello properties!

You may have noticed that we didn’t set the text of strategyTextView this way:

The code above compiles and works, but getters and setters are idioms from Java, not Kotlin, and Android Studio will remind you of that fact:

Instead of the setText and getText methods, simply use the text property:

Under the hood, Kotlin implements getter and setter methods, but all you taste is the sweet and concise syntactic sugar of property access.

Declaring variables and instantiating objects

Our app randomly selects from a list of strings, which means that we’ll need an instance of the Random class:

Note the following:

  • The keyword val declares random as read-only. If you want to declare something as both readable and writable, use the var keyword instead.
  • We didn’t have to specify random’s type. Kotlin infers it from the value that Random() returns.
  • We didn’t use the new keyword to create a new instance of Random; we simply used Random(), which is a reference to Random’s no-parameter constructor.

You probably notices that with Kotlin, you no longer have to deal with this sort of redundancy:

We’ll also need to read the contents of oblique_strategies.xml into an array, which we can do with this line:

Note the following:

  • Since we’re only going to read from this array and not write to it, we declare it using the val keyword, as opposed to the var keyword. Remember this mantra that Swift programmers have taken to heart (using slightly different keywords): val where possible, otherwise use var.
  • Again, we don’t have to specify the type of strategies; it’s inferred from getStringArray’s return type.

Now that we’ve got…

  • random, a random number generator,
  • strategies, an array containing strategies, and
  • strategyTextView, a reference to the textView where randomly-selected text strategies should be displayed…

…choosing a random strategy and displaying it is as simple as this…

…and the MainActivity class is as simple as this:

For comparison’s sake, here’s what the app’s code would’ve been, had it been written in Java:

Before you dismiss this example as a toy app…

…do a search for “Oblique Strategies” in the Play Store. You’ll be amazed at how many implementations there are — and now you can do one with a mere four lines of code.

Watch this blog for more Android development in Kotlin!

In addition to my regular articles about iOS development in Swift, Global Nerdy will also start featuring regular articles on Android development in Kotlin. Watch this blog — there’s lots of interesting stuff coming soon!

{ 1 comment }

Here’s what’s happening for developers, technologists, and tech entrepreneurs in and around the Tampa Bay area this week…

Monday, May 22

Tuesday, May 23

Wednesday, May 24

Thursday, May 25

Friday, May 26

Saturday, May 27

Sunday, May 28

{ 0 comments }

Harvest’s poignant tribute to Chris Cornell

by Joey deVilla on May 19, 2017

I’m doing some contract work for a local mobile development shop who use Harvest as their time-tracking app (and it’s a nice one, too!). On days where you haven’t made any entries, Harvest fills the blank space with an aphorism or inspirational quote.

Currently, in honor of Chris Cornell, the quote is “One more time around might do it,” a lyric from one of Soundgarden’s best songs, The Day I Tried to Live:

This is cloud software’s way of pouring a 40 on the ground for fallen homies.
Click the screenshot to see it at full size.

After taking in that poignant moment — at Crazy Go Nuts University, I was a DJ at the engineering pub and a keyboard player in an alt-rock band, and Soundgarden figured heavily in both — I did what I was supposed to do: click New Entry, put on some Soundgarden, and get to work on coding. This software isn’t going to write itself.

Have a productive Friday, everyone!

{ 0 comments }

Texas Instruments’ famous last words

by Joey deVilla on May 15, 2017

Texas Instruments should have simply issued this statement
to upstart online calculator vendor Desmos.

If you don’t get what “welcome to your tape” means, keep reading!

In response to the existential threat that free online graphing calculator startup Desmos is to old-school physical calculator manufacturer Texas Instruments (often called “TI” for short), here’s what TI’s president of education technology had to say in a recent Bloomberg News story:

“Our products include only the features that students need in the classroom, without the many distractions or test security concerns that come with smartphones, tablets and internet access.”

Remember that quote. “We’re better because we do less and charge more for it” is often the battle cry of a slow-moving, complacent incumbent about to be trounced by an upstart that’s aware of changing technologies and markets.

Desmos got their first serious public exposure when they launched at TechCrunch Disrupt NYC in 2011 as a platform for collaborating on lessons plans and building and publishing interactive lessons. Even then, they had Texas Instruments in their sights — at their launch, Desmos founder Eli Luberoff said “Texas Instruments, your monopoly on graphing in the classroom is over.”

Since then, they’ve:

With all this and the fact that physical calculator tech hasn’t changed much in power or price over the past 20 years while mobile tech has advanced in leaps and bounds, Desmos is on track to displacing Texas Instruments as the calculator of choice for high school and university.

Okay, please explain “Welcome to your tape”

It’s a new catchphrase that comes from the Netflix series 13 Reasons Why, which is about a high school student’s decision to commit suicide. Hannah Baker, the student in question, left behind a collection of cassette tapes explaining the thirteen reasons why she killed herself. Each tape addressed a specific student in her class and opened with “Welcome to your tape, [student’s name here]” — basically a message that says “You are one of the reasons why I chose suicide.”

As you should have come to expect, “Welcome to your tape” has been memed.

 

{ 0 comments }

Here’s what’s happening for developers, technologists, and tech entrepreneurs in and around the Tampa Bay area this week…

Monday, May 15

Tuesday, May 16

Wednesday, May 17

Thursday, May 18

Friday, May 19

Saturday, May 20

Sunday, May 21

{ 0 comments }

Here’s what’s happening for developers, technologists, and tech entrepreneurs in and around the Tampa Bay area this week…

Monday, May 8

Tuesday, May 9

Wednesday, May 10

Thursday, May 11

Friday, May 12

Saturday, May 13

Sunday, May 14

{ 0 comments }