Creating Instances of Classes

Java and Ruby both use new to create instances of classes, whether as a keyword in Java:

Foo foo = new Foo();

…or as a method in Ruby:

foo = Foo.new

JavaScript has a few flavors of creating objects, including one using the new keyword, much as you would in Java.

In Kotlin, though, you treat the class name as a function name, and just call it:

class Foo

fun main() {
  val foo = Foo()

  println(foo)
}

In effect, you are calling the class “constructor” this way — we will explore constructors more later in this chapter.

The println() call does not print much:

[object Object]

That is partly due to the limited built-in implementation of the toString() function that we inherit, and partly due to limitations in the Kotlin scripting environment used by Klassbook.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.