Why does Kotlin use a way of declaring functions and variables other than "traditional"?

Asked

Viewed 308 times

8

Traditionally the return type and variable type are indicated at the beginning, before the name:

public int soma(int a, int b){
    return a + b;
}

In Kotlin he is named after:

fun sum(a: Int, b: Int): Int {
    return a + b
}

What are the reasons behind this option?

  • 4

    I don’t think it’s a revealing motive or anything like that. I believe it’s a semantic differential only. As in php for example we declare variables with the $ in front and changes absolutely nothing. Only semantics rs.

2 answers

7


Exactly, this "traditional" right between quotation marks. The way you call traditional comes from the C style, which is considered bad by many.

Complicates compiler because it generates context for parser, hinders the inference of types, requires a keyword before the statement when does not mean the type (although Kotlin erred in this, in my opinion*).

Many people also consider it more readable so it gets more fluid. The variable name is more important than its type. In fact in types like big names until you find the variable name is a sadness:

val shapeInfo: HashMap[Shape, (String, String)] = makeInfo()
val HashMap[Shape, (String, String)] shapeInfo := makeInfo()

I put in the Github for future reference.

Which you find the variable name more easily?


*I’d prefer something like this:

variavel := 1
constante ::= 1
variavel : Int

Easier to find the name, right? Always in column 0.

Identifiers are very important in the code, giving visibility to them is critical.

4

To FAQ had an answer regarding this, but was removed:

Why have type declarations on the right?

We Believe it makes the code more readable. Besides, it Enables some nice syntactic Features, for instance, it is easy to Leave type Annotations out. Scala has also proven Pretty well this is not a problem.

Or, in free translation:

Why type statements on the right?

We believe it makes the code more readable. Moreover, it allows the addition of some interesting syntax features. It’s easy, for example, to set aside type annotations. Scala also proved that this is not a problem.

  • "type declarations" -> "type annotations"? I would prefer to translate as "type statements". In addition, the word "nice" was lost in translation, I suggest putting it as "interesting" or "good".

  • @Victorstafusa thanks for the suggestions!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.