Ondo
Ondo

Reputation: 45

What the diffrence between thoses declaration - Kotlin

I'm trying to create an application for fun (in Kotlin, on Android Studio), I tried different syntaxe for initialise my var nb.

The first case works but for the second I have This variable must either have a type annotation or be initialized, and i would like to know why.

Thanks for your answer

var nb = Random().nextInt((30 - 0))

var nb2
nb2 = Random().nextInt((30 - 0))

Upvotes: 0

Views: 161

Answers (4)

Sun Jiao
Sun Jiao

Reputation: 350

In your first declaration, kotlin auto cast nb to Int, because type of Random().nextInt((30 - 0)) is Int.

In kotlin, when you join assignment and declaration within 1 line, it will be auto cast to the type of assigned value.

But if you seperate them in 2 lines, it will not work. You'd specify its type manually.

var nb2 : Int
nb2 = Random().nextInt((30 - 0))

Upvotes: 1

Công Hải
Công Hải

Reputation: 5261

You must specific type for variable when declare in kotlin, because kotlin is Static typed languages. In the first case kotlin auto know what type of variable. In second case, it doesn't know type

Upvotes: 1

forpas
forpas

Reputation: 164194

You can't declare a variable without either defining its data type:

var nb: Int

or initializing it:

var nb = Random().nextInt((30 - 0))

in which case its data type is inferred by the data type returned from the expression that is assigned to it, in this case Int.

Upvotes: 5

MMG
MMG

Reputation: 3268

For second one, try this:

var nb2:Int
nb2 = Random().nextInt((30 - 0))

You specify first that your variable is Int and then you will give value to it.

Upvotes: 5

Related Questions