Main differences:
- In Kotlin function sane
first-class citizens
, that is, the language allows to manipulate functions with the main, if not all, operations available to other entities: passage of arguments, return of functions, modifications, assignment of variables, etc... This allows us to use some concepts of functional programming such as: pure functions, functions without side effects; high-order functions, which take functions as parameter, as return, or as both; immutability, where internal states remain unchanged, including the collections
of language.
Example 1:
fun callAction(action: (String) -> Unit) = action("Hello world!")
fun printMessage() = callAction { text -> println(text) }
printMessage()
Example 2:
// Ou utilizando a referência do método
fun callAction(action: (String) -> Unit) = action("Hello world!")
fun printMessage() = callAction(::println)
printMessage()
Example:
infix fun Int.plus(text: String): Int = this + text.toInt()
println(1 plus "2")
// é o mesmo que
println(1.plus("2"))
- Kotlin supports extension functions, that give us the ability to extend a class with a new functionality without having to inherit from it, or use any kind of project pattern like Decorator.
Example:
import java.math.BigDecimal
fun Int.toBigDecimal() = BigDecimal(this)
println(4.toBigDecimal())
- Kotlin supports operator overload, which allows us to provide implementations for a predefined set of operators in our types. Full list of operators can be found here.
Example:
data class Money(var value: Int)
operator fun Money.plusAssign(value: Money) {
this.value += value.value
}
val money = Money(10)
money += Money(20)
println(money.value) // 30
- Kotlin owns date-classes, similar to the case-classes in Scala, which facilitates the creation of classes that often serve only to store data like DTO’s or POJO’s. In this case the compiler will derive the members declared in the primary constructor and implement:
equals
, hashCode
, toString
and copy
. With them we can disrupt declarations, similar to destructuring assignment of Ecmascript6. We can also identify patterns with data-classes
using the Pattern-matching of language.
Example:
data class User(val name: String, val age: Int)
val jane = User("Jane", 35)
val (name, age) = jane // destructuring declaration
println("$name, $age years of age") // prints "Jane, 35 years of age"
- Kotlin owns Sealed-classes, which are used to represent hierarchies of restricted classes, when a value may have one of the types of a limited set, but may not have any other type. They are, in a sense, an extension of enumerated classes: the set of values for an Enum type is also restricted, but each constantEnum exists only as a single instance, while a subclass of a sealed class may have multiple instances that may contain state.
Example:
sealed class Expression {
data class Const(val number: Double) : Expression()
data class Sum(val e1: Expression, val e2: Expression) : Expression()
object NotANumber : Expression()
}
fun eval(expr: Expression): Double = when (expr) {
is Expression.Const -> expr.number
is Expression.Sum -> eval(expr.e1) + eval(expr.e2)
Expression.NotANumber -> Double.NaN
}
Example:
val x: String = ""
val y : String? = null
println(x.length) // 0
println(y?.length) // null
y?.let(::println) // println não é chamado porque y é nulo
Notes:
- In summary, Kotlin allows us to implement concepts from the Object-Oriented Programming paradigm as well as Functional Programming, allowing us to extract the best of both worlds, with a concise and yet incredibly powerful language.
- Being a little pragmatic, everything you do with Kotlin can be done with Java, in terms of features, but I believe that Kotlin becomes better in terms of practicality, simplicity and productivity.
- For those interested in learning the language, there is Kotlin Koans where are passed some challenges and you have to do them.
- Language documentation site: kotlinlang.org
- Language specification document: kotlinlang.org/Docs/Kotlin-Docs.pdf
In addition to the points cited, there are several other concepts that are interesting, but that I did not put here not to extend me more.
I know Docs are bad and tals, but the most I could do is translate, but I don’t guarantee the translation, so I’ll just post the link https://kotlinlang.org/docs/reference/comparison-to-java.html
– TotallyUncool
This post addresses some of the aspects in relation to what "Kotlin can offer/solve/improve in relation to Java"
– ramaral
The answers seem to be getting outdated, right? Java started having some things and there are some that will have a brief.
– Maniero