develop with

Basics

Kotlin variables, methods, class, modules

Kotlin’s programming style consists of camel case for variable and method naming. Classes and modules follow a camel case style. Kotlin allows for organization of your application into packages, classes or straight functional programming approaches. Unlike Java semicolons are not needed for ending lines. The typing system within Kotlin follows the approaches in Java related to object types and interfaces.

Comments

Commenting and documenting code is an important part of coding and Kotlin uses the /* start and *\ end as comment delineators much like C++ or Java. You can also add // as the first characters of your line to make it into a comment which means it doesn’t have any functional value to the application. It is used to provide a way to describe what some part of the application is doing.

Variables

A variable is storage location for a value that you will use across your application. In Kotlin there are various variable visibilities including public (default), internal and private.

Example of public variable:

var myValue = " hello "

Example of internal variable:

class MyClass {
  internal var myValue= "hello"
}

Example of private variable:

class MyClass {
  private var myValue= "hello"
}

There is also the concept of mutable and immutable variables in Kotlin. The var definition is a mutable variable, whereas val defines the value as immutable.

Example of immutable variable:

val myValue = " hello "

If a value is declared immutable (think final in Java), you will need them define a variable unless the variable is marked as lateinit. Lateinit referes to a variable being set after the class is initialized and constructed. Lateinit or variables defined without a value will need to have the type defined with them.

For example:

class MyClass {
 lateinit val myValue:String

  init() {
    myValue = "hello"
  }

}

By default getter and setters are defined for variables of a class.

Methods

Methods provide a way to organize functional parts of your application into logical sections. They give you the ability to add functionality to data as well as processing of data in various ways. An explicit return and return type will need to be defined when returning values. Arguments can be defined on the method via parens.

Example method:

fun world() : String
  return "hello"
end

fun worldNoReturn()
  // method without a return
end

Example method with arguments:

def world(hello:String) : String
  // return variable
  return hello
end

Next: Conditions and Switches

comments powered by Disqus

Want to see a topic covered? create a suggestion

Get more developer references and books in the developwith store.