Showing posts with label first impressions. Show all posts
Showing posts with label first impressions. Show all posts

Monday, July 11, 2022

Code: Kotlin First Impressions

Introduction
Kotlin is one of the newest and most popular JVM languages and it might be one of my new favorite languages. Disclaimer: I haven't written much production-ready code in it yet.

As a JVM language like Scala, Groovy, and Clojure; Kotlin tries to take the portability of the Java Virtual Machine and familiarity of the Java language while improving upon its archaic design with the conciseness and power of modern programming languages. Simply put: it's Java but better—for real this time!

Scala was my favorite attempt at improving Java, but I was pretty unhappy with the build system. Since Kotlin is written by JetBrains, an IDE company, compiler and IDE support is first-class. You can even use JetBrains' IntelliJ to output Kotlin code to Java, and vice versa. For this reason alone, it is easy to pick up for Java developers.

Improvements on Java 8
So what does Kotlin improve upon? Firstly, Java's verbosity. Compare a hello world program in Java:

public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("Hello world!");
  }
}

and in Kotlin:

fun main() {
    println("Hello world!")
}

The first thing to note is that no class definition is required. You can simply add top-level functions. Kotlin is a functional language, so a function definition is required, but the public access modifier is implied. Top-level functions are always static. And type inference also applies to functions, so no void is required here. Just fun to mark that it's a function. In the actual function itself, println is a top-level function, so no need to qualify the function with a package and class. Lastly, no semicolons.

This is not some neat trick about hello world programs, the rest of the language is written to be concise. Record classes (data classes), raw strings, type inference, default function parameter values, string interpolation, collection builders, array slices, range operators, and null safety operators all help make your code very concise and efficient. If you don't know what those mean take the following Kotlin code:

fun doSomething(param: String = "default") {
  val stringTemplate = "$param ${1 + 2} String"

  val nums = (0..20).toList() // A list of integers from 0 to 20
  println(nums.slice(1..5 step 2)) // Prints "[1, 3, 5]"

  val newStr: String? = getStringOrNull()
  println(newStr?.length) // Prints length or "null" if string is null

  val neverNull = getStringOrNull2() ?: "" // Converts nulls to ""

  val regex = """\w+@gmail\.com"""
}

Doing this in Java 8 without special libraries would be like:

public static void doSomething() {
  doSomething(null);
}

public static void doSomething(String param) {

  param = (param == null) ? "default" : param;
  String stringTemplate = String.format("%s %d String", param, (1 + 2));

  List<Integer> nums = IntStream.rangeClosed(0, 20).boxed()
      .collect(Collectors.toList()); // It's either this or a for loop

  // A for loop is simpler than the stream version
  List<Integer> slicedList = new ArrayList<>();

  for (int i = 1; i <= 5; i += 2) {
    slicedList.add(nums.get(i));
  }
  System.out.println(slicedList); // Prints "[1, 3, 5]"

  String newStr = getStringOrNull();

  System.out.println((newStr == null) ? null : newStr.length());

  // We need two lines for this, unless we call the function twice
  String intermediateVar = getStringOrNull2();
  String neverNull = (intermediateVar == null) ? "" : intermediateVar;

  String regex = "\\w+@gmail\\.com"; // We must escape special characters
}

Or at least that's my interpretation. With Java 8 streams, there are a few functions to create and manipulate collections. You can also short circuit nullable objects with Optional.ofNullable([nullable]).orElse([default]), but I prefer the ternary operator in Java.

Another great feature is destructuring declarations. In Python, you can return multiple values. In Kotlin, we get half of that feature by being able to "destructure" a returned value into multiple variables:

  val (name, age) = person
  for ((key, value) in map) {
    // stuff
  }

Lastly, it is interoperable with Java. You can call Java code from Kotlin and you can even call Kotlin code from Java. One of Java's biggest strengths is the massive set of libraries you can use. These libraries are available, too, in Kotlin.

Drawbacks
Sounds too good to exist? Well, Kotlin has some drawbacks. I probably will come up with more after using the language for a while, but for right now, the drawbacks are minimal.

For one, variable type declarations follow the variable name as in var a:Int. For many of us, we started programming in C, C++, or Java where variable types come before the variable name. I disliked this seemingly arbitrary change until it was explained to me.

When declaring a variable, the variable's name is the most important aspect. When your language has type inference, the type isn't always written. This means variables declarations are generally aligned well, regardless of type declaration or lack thereof. This alignment is maintained for variables (val or var) and functions (fun).

val a = 1   // Infers type from value
val b: Int  // No value to infer type
var c: String = "String" // Optionally specify type
// Infer return type of single-expression function
fun sum(arg1: Int, arg2: Int) = arg1 + arg2

Notice that the val/var/fun keywords are all aligned vertically, as are the names. So while this name-type order will take some getting used to, it's not a bad thing. Pretty much all modern languages (Go, Rust, Swift, Scala, Nim, and Python) use it.

One issue that I dislike is the amount of scope functions. let, run, with, apply, and also are all ways to call a block of code with a temporary scope and each is used slightly differently. This seems like overkill and I don't imagine I'll ever memorize which is which. You don't want to have too many ways to do the same thing in a language, as it makes reading and reviewing code difficult.

Overall, it seems like a very fun, concise language and an upgrade to Java.

Kotlin vs Newer Versions of Java
JetBrains 2021 Developer Study


Having said that, Java has progressed quite past version 8. Java 8 is still the most popular version, according to a JetBrains survey, being used by 72% of Java programmers (users were allowed to select multiple versions). SNYK's survey results says Java 11 slightly outweighs Java 8 with both being around 61%. In either case, the higher versions of Java have little use with both companies saying Java 15 use is around 13%.


SNYK 2021 Developer Study

Java 19 will drop in September, but for a company looking for stability should probably stick with Java 17, as it is will still be the most recent version with Long-Term Support from Oracle. So what does Java 17 add to the language that Java 8 and Java 11 users may be unfamiliar with? I will describe some of the notable language updates, ignoring preview features and compiler and JVM enhancements.

Java 9 to 11 updates:

  • 9: Project Jigsaw: Modular system
    Introduces a module system to the language to define exports and dependencies.
  • 9: Private methods in interfaces
  • 9: Actual immutable collections
    Allows things like Set.of(item1, item2).
  • 10: Type inference
    Introduces var keyword.
  • 10: Root certificates.
    Allows TLS out of the box.
  • 11: HttpClient
    A replacement for HttpUrlConnection.
  • 11: More String and Files methods
    New methods like String::lines and Files::readString.
Java 12 to 17 updates:
  • 12: New methods in String, Files, and Collectors
  • 12: A number formatter
  • 14: Switch expressions
    Makes switch expressions much less verbose.
  • 15: Text blocks
    Allows setting Strings to nicely-formatted multiline blocks of text without inserting pesky "\n".
  • 16: Records
    Allows the creation of data classes with default getters and setters in essentially one line.
  • 16: Pattern matching for instanceof
    Decreases verbosity by allowing the declaration of a variable in an instanceof expression.
  • 17: Sealed classes
    Increases control over class inheritance.
Most of this article was written with Java 8 in mind. It's fair to say that Java has come a long way since then and Java now has more syntactic sugar. Specifically, type inference, text blocks (multiline strings), and records (data classes). However, even these new features are weaker than their Kotlin equivalents:
  • Type inference only applies to local variables, not top-level variables or lambda expressions
  • Text blocks aren't raw strings and will still process escape sequences (i.e. you still have to escape all of your backslashes). Writing regex in Java still sucks.
  • A record cannot contain any private instance variables. Admittedly, this is a tiny disadvantage.
Even the work that has been done to modernize Java doesn't bring it up to par with Kotlin. That's why I'm excited to start using Kotlin.

Friday, August 3, 2012

First Impressions: Galaxy Nexus


Tired of my HTC EVO 3D, I made a huge list of pros and cons of getting new phones on each of the networks (except AT&T). Long story short, I decided to get the unlocked GSM Samsung Galaxy Nexus through Google's Play Store and use it on T-Mobile. I'd talked to a lot of people and the awesomeness of a new Samsung Galaxy S III couldn't match the awesomeness of getting guaranteed OS updates first from Google before everyone else. This seemed to make sense to me after my EVO 3D's official Android 4.0 (Ice Cream Sandwich) port was delayed over and over again, from its original "early 2012" release date to June to early August. Also important was that that a brand new GSM Galaxy Nexus was super cheap, compared to other similarly-spec'ed smartphones.

Since I'm avoiding AT&T because of their crap reception and anti-tethering policies, the only option was T-Mobile. This was perfect because I'd read that T-Mobile, unlike every other national carrier, had no-contract plans that were cheaper than the contract plans. The reason: contract plans come with that ~$400 phone discount so customers can get ~$200 phones. But I was bringing my own phone. I bought the phone and got T-Mobile service the day after the phone arrived.

Initially, this experience was met with disappointment. While the Android 4.1 (Jelly Bean) update came to my phone soon after I turned it on, it is a pretty insignificant upgrade. While the phone does seem very zippy and I don't notice any lag, I barely used it while the phone was still on Ice Cream Sandwich, so it's hard to say definitively if Ice Cream Sandwich was any slower than Jelly Bean. Google Now, which seemed to be billed as Google's answer to Siri and S-Voice, seems to be little other than an app to display commute time and the weather.

There were more issues: I was once told that rooting a Nexus was simple: you just check a box. This appealed to me. As technical as I am, I would prefer a phone that didn't require jailbreaking or hacking to get it to do what I want. Jailbreaking my iPhones and rooting my EVO 3D were tedious, scary processes that could've easily resulted in me turning my phone into a brick. I looked forward to a simple rooting process that was sanctioned by my phone. But I was misled. Rooting even a GSM Nexus is a process filled with many steps and involving a PC.

Then, while I have complained about the manufacturers' skinning of Ice Cream Sandwich, it seems that stock ICS/Jelly Bean is still a little barebones. Google's apps just aren't there yet. I miss Swype and the EVO's trace keyboard, which I didn't realize weren't available on stock Android. I hate that Google's contacts app (People) doesn't let you filter out your Google+ contacts and other people without phone numbers. I cannot believe that you are stuck with 5 pages on the home screen; no more no less. I will probably end up using some sort of 3rd party launcher, if I don't use a different ROM entirely.

The T-Mobile experience is also somewhat lacking. I found out in the store that my no-contract plan is actually more expensive than the contract plan. I wanted 500 minutes, unlimited text and 2 to 5 GB of fast 4G data. Both the 2 GB and 5 GB plans are cheaper on contract. I had been looking at the Value plans at T-Mobile, which require a 2-year contract. Instead, I needed a Prepaid/Monthly plan, which has a different website and a different set of rules. I've always been scared of prepaid carriers, but the sales rep assured me that I'd be using T-Mobile towers and would have the same reception, although she mentioned that 4G wasn't as good.  I soon would find out that prepaid and monthly customers can't use T-Mobile's visual voicemail app.

Lastly, T-Mobile's 4G claims are a little off.  They have many posters in the store and online that claim "42 MBPS SPEEDS ON T-MOBILE."  I now realize they write these claims in all caps so people will think they mean "42 MBps" or megabytes per second, instead of "42 Mbps" or megabits per second.  42 MBps is 8 times faster than 42 Mbps.  That didn't matter much, because 42 Mbps is still pretty fast and is over 4 times faster than my home internet connection.  But my max speed on T-Mobile's HSPA+ is 7.22 Mbps.  Definitely better than my Sprint WiMAX max of around 5 Mbps, but hardly 42 Mbps.

However, everything else about the phone is awesome. It's super fast, the SAMOLED screen has a beautiful contrast and is brighter in direct sunlight, the gorgeous HD display looks like a Retina Display to me, the back camera is better and super fast, using MTP to transfer files instead of mounting as an SD card seems to be better in most ways, and the battery is better than the EVO 3D.  Even without 4G turned on, my EVO 3D consumes battery life quicker than the Nexus does with 4G turned on.  So, better battery life and 4G speeds to boot.  I also like the build of the phone.  I was a little uneasy about the rapidly increasing sizes of phones these days, but the Galaxy Nexus feels and looks awesome in my hand.  Even the monthly plan is technically cheaper, as long as I leave T-Mobile in less than 12 months, because of the lack of an early termination fee.  I miss visual voicemail, a feature I've enjoyed since my first iPhone in 2009, but supposedly Google Voice will allow me to get visual voicemail again.

Is the Galaxy Nexus better than the Galaxy S III?  Probably not.  Is T-Mobile better than Verizon? The 4G is definitely slower, but the 4G is less battery-consuming and the plans are definitely cheaper. Will this do until I can get a new phone in a year or less? Definitely.

Monday, November 28, 2011

First Impressions: HTC Rezound


This is not a formal review, but a list of initial thoughts on the device.

The HTC Rezound for Verizon is a true media phone. Great screen, good sound... though, for some reason, HTC neglects to advertise the gorgeous screen on this phone.  It has a pixel density greater than the iPhone's Retina Display, yet you'd never know it by watching HTC's commercials.  Instead, they insist on only advertising the audio capabilities of the phone, which are indeed decent.  The speaker is certainly a step up from the HTC EVO 3D's tinny speaker (my EVO 3D review is coming shortly).

But that's just it.  The speaker is decent, not great, not game-changing, and definitely not a preferred way to listen to music, even the music you store on the phone.  The speaker is still a tiny phone speaker and it sounds no better than your laptop--which also may be rocking Dr. Dre's Beats. I wonder how much more money Dr. Dre is going to make on Beats until the rest of the populace realize what audiophiles have been telling me for years: his products are marginal upgrades on the speakers and headphones that you pick out of the bargain bin at Marshall's.  But I digress.

The HD (1280 x 720 pixels) screen makes the Rezound the first HD phone in the US, soon to be followed by the Galaxy Nexus.  However, unlike the Galaxy Nexus, HTC crams all those pixels into a 4.3 inch screen, meaning it has a pixel density of 342 ppi.  This bests even the iPhone's screen (330 ppi).  It has a better pixel density than any phone announced, including the Galaxy Nexus.

The only drawback?  Most of time you probably won't notice it.  Unlike the iPhone, where stock apps appear with high resolution, Android 2.3 and Sense 3.5 aren't taking advantage of this high resolution screen.  Instead, the home screen has the typical, pixel-y apps and widgets.  The only places where you can see the density shine are pictures, video, and small text in webpages.  I took some pictures and looked at one of the videos on the device and they were gorgeous.  I took a picture of my hand and not only could I see my skin cells, I could see into the future where liver spots are going to appear in 60 years.  Well, almost.

HD wallpapers also look great on this.  There's a Beats wallpaper that comes with the phone and it looks awesome.  If only it weren't hidden behind those icons and widgets.

Sense 3.5 comes on this phone, which has its downsides.  One downside is that they've needlessly rearranged some HTC app settings, like the camera and general phone settings.  Sense also means this phone won't get Android 4.0 (Ice Cream Sandwich) for at least a few months.  And while Sense is the most beautiful manufacturer skin and certainly prettier than Gingerbread, I doubt it's prettier than Ice Cream Sandwich will be.  I'm having trouble thinking of any upsides to Sense 3.5.  Perhaps, the software rearrangement will prove to be a benefit when a user gets used to it.

No dedicated camera button.  Lame.

To sum up, don't buy this.  Get the Galaxy Nexus instead, which is certain to drop in December or January, since it's already being sold in other countries.