Kotlin Classes and Interfaces Tutorials

      1 Comment on Kotlin Classes and Interfaces Tutorials

An interface is nothing more than a contract; it contains definitions for a set of related functionalities. The implementer of the interface has to adhere to the interface the contract and implement the required methods. Just like Java 8, a Kotlin interface contains the declarations of abstract methods as well as method implementations. Unlike abstract classes, an interface cannot contain state; however, it can contain properties. For the Scala developer reading this book, you will find this similar to the Scala traits:

interface Document {
val version: Long
val size: Long
val name: String
get() = "NoName"
fun save(input: InputStream)
fun load(stream: OutputStream)
fun getDescription(): String {
return "Document $name has $size byte(-s)"}
}

This interface defines three methods. The name property and the “getDescription” methods provide the default implementation. How would you use the interface from a Java class? Let’s see by implementing this interface: public class MyDocument implements Document {
public long getVersion() {
return 0;
}
public long getSize() {
return 0;
}
public void save(@NotNull InputStream input) {
}
public void load(@NotNull OutputStream stream) {
}
public String getName() {
return null;
}
public String getDescription() {
return null;
}
}

You can see the properties have been translated into Getters. Despite providing default implementations for
getDescription along with the name, you still have to implement them. This is not the case when implementing the interface in a Kotlin class:

   class DocumentImpl : Document {
      override val size: Long
      get() = 0
      override fun load(stream: OutputStream) {
      }
      override fun save(input: InputStream) {
      }
      override val version: Long
      get() = 0
    }
It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn