Coding in New Age Programming Languages for Mobile Development-Kotlin & Swift

Ever since Google announced to support Kotlin officially and started to ship along with the Android Studio, the development community is excited to work with the new-age programming language. Being worked with Java for Android, Carbon, Cocoa framework for Mac, and UIKit framework for iOS, we would like to share how Kotlin and Swift programming languages exciting for mobile developers.

While Kotlin has started to become more popular in Hashtaag™ lab for Android development, Swift has been mainstream programming language with all iOS mobile products development.

Here are a few common things about new-age programming languages which make programming pleasant for our developers:

  1. Lean Syntax
  2. Null Safety
  3. Emphasis on Functional Programming
  4. Simplification with Operator overloading
  5. Interpretation of asynchronous programming

Even though Kotlin and Swift are intended for different platforms, we would like to discuss with hacker programmers who are curious beyond languages, platforms.

Singleton

Kotlin

Generally, static members are used in all programming languages to create singleton objects. Kotlin does not have a static keyword. Kotlin singleton design represents “Object”, not “Class”.

object Singleton {

init {

println("This ($this) is a singleton")

}

var b:String? = null

}

Kotlin takes care of the following design principles for Singleton:

  1. Constructor is not allowed.
  2. Object declarations are created immediately at the point of definition, not through the constructor. So defining a constructor, in this case, doesn’t make sense.
  3. Single-time instance creation.
  4. Global access of that instance.
  5. Thread-safe (developers needed to ensure synchronization in Java)

Swift

Swift uses dispatch_once to perform thread-safe lazy initialization of global variables and static properties, hence we have simple syntax for creating Singleton in Swift.

class Singleton: NSObject {

static let sharedInstance = Singleton()

private override init() {}

}

let singleton = Singleton.sharedInstance

Make sure init() is private so that the creation of another instance is prevented.

It is thread-safe. sharedInstance is a class variable, that is having reference to the object of type Singleton; the only object of type Singleton.

Named Arguments and Default Arguments

These are simple yet very useful programming tweaks in making modular programming. When we try to make reusable modules we would be expecting flexibility to generalize the parameters. Default Arguments and named Parameters exactly serve the same

Kotlin

class InboxMail(val from:Sting = "sid@hashtaag.com"

vararg to:String

val subject:String

val body:String){

}

val inbox1 = InboxMail(“sujoy@hashtaag.com”, "hello@hashtaag.com", "On New features of kotlin", “All description goes here”)

val inbox2 = InboxMail(to: "hello@hashtaag.com", "On New features of kotlin", “All description goes here”)

In the second call to InboxMail, we are not providing the first argument and explicitly naming the argument name for the second. This is called “Named Arguments Id”. We do not specify named arguments while using default values compiler gives error.

Swift

Each function parameter has both an argument label and a parameter name. The argument label is used when calling the function; each argument is written in the function call with its argument label before it. The parameter name is used in the implementation of the function. By default, parameters use their parameter name as their argument label.

func someFunction(firstParameterName: Int, secondParameterName: Int) {

// In the function body, firstParameterName and secondParameterName

// refer to the argument values for the first and second parameters.

}

someFunction(firstParameterName: 1, secondParameterName: 2)

You write an argument label before the parameter name, separated by a space:

func someFunction(_ firstParameterName: Int, secondParameterName: Int) {

// In the function body, firstParameterName and secondParameterName

// refer to the argument values for the first and second parameters.

}

someFunction(1, secondParameterName: 2)

If a parameter has an argument label, the argument must be labeled when you call the function.

Default Arguments

You can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type. If a default value is defined, you can omit that parameter when calling the function.

func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int = 12) {

// If you omit the second argument when calling this function, then

// the value of parameterWithDefault is 12 inside the function body.

}

someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6

someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12

Returning Multiple Values

There are many scenarios where multiple return values are useful. Multiple return values are so convenient that programmers usually find ways to simulate them even in languages that don’t support them directly. As for new programming languages, most of them come with this feature natively supported.

Kotlin

JVM does not allow returning more than one value from a function, so all we can do is return a Pair/Triple/Whatever. We can smartly get this done like this:

// Make error optional and default it to null

data class Result(val result: String, error: String? = null)

// Do some task to get a result

fun getResult(): Result {

// error 

if (something == "gone wrong") {

   return Result("No result", "Something went very wrong")

}

 return Result(" you got the result you wanted")

}

// You now have a result and error to do what you want with

val (result, err) = getResult()

Swift

Swift provides tuple type, which can be used as the return type for a function to return multiple values.

The example below defines a function called minMax(array:), which finds the smallest and largest numbers in an array of Int values:

func minMax(array: [Int]) -> (min: Int, max: Int) {

       var currentMin = array[0]

       var currentMax = array[0]

       for value in array[1..<array.count] {

           if value < currentMin {

               currentMin = value

           } else if value > currentMax {

               currentMax = value

           }

       }

       return (currentMin, currentMax)

   }

The minMax(array:) function returns a tuple containing two Int values. These values are labeled min and max so that they can be accessed by name when querying the function’s return value.

Because the tuple’s member values are named as part of the function’s return type, they can be accessed with dot syntax to retrieve the minimum and maximum found values.

let result = minMax(array: [18, -26, 24, 179, 43, 101])

print(“Min is \(result.min) and Max is \(result.max)")

Extension

Traditionally while coding in java and objective C developers use to write a lot of utility functions to use commonly across the projects. It was a sort of non-objective approach. Also, maintainability with multiple developers was always a challenge.

With extensions, we would be able to add extra functions to the Framework classes

Kotlin

Extension Function:

Extension function as the name implies it helps us to extend the functionality of classes without having to touch their code. Now let’s see how these functions are defined.

How can you define an extension function?

Just write a function as you would normally, and put the name of the class before separated by a point. These functions can be everywhere, usually in an Extensions file which doesn’t even need to contain a class.

Very simple example: we want to make a view have the visible(), which makes it visible. We would write something like this:

fun View.visible() {

this.visibility = View.VISIBLE

}

Extension properties:

Just as you can do extension functions, so can you do with properties. The only thing you need to remember is that extension properties can not save state but will need to use existing functions to request or modify the state of the object.

Swift

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

Extensions in Swift can:

1. Add computed instance properties and computed type properties

2. Define instance methods and type methods

3. Provide new initializers

4. Define subscripts

5. Define and use new nested types

6. Make an existing type conform to a protocol

Extensions can add new functionality to a type, but they cannot override existing functionality.

If you define an extension to add new functionality to an existing type, the new functionality will be available on all existing instances of that type, even if they were created before the extension was defined.

extension SomeType {

// new functionality to add to SomeType goes here

}

Questions?

Reach out to us at: hello@hashtaag.com