HelloCW
HelloCW

Reputation: 2345

Why can I define a var without a class in Kotlin?

I define a var b in the file myClass.kt which isn't contained any class, and the app can run correctly.

It seems that the var b is just like static var in Java, right?

Main

package com.example.dagger.kotlin.ui
class HomeActivity : DemoActivity() {
    @Inject
    lateinit var locationManager: LocationManager

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        (application as DemoApplication).component.inject(this)

        // TODO Do something with the injected dependencies here
        locationInfo.text = "Injected LocationManager:\n$locationManager"


        Toast.makeText(this, b, Toast.LENGTH_LONG).show();

    }



}

myClass.kt

package com.example.dagger.kotlin.ui
var  b="New Girl"

Upvotes: 0

Views: 74

Answers (1)

guenhter
guenhter

Reputation: 12177

If you decompile the resulting .class file, you will get:

public final class myClassKt { 
  @NotNull
  public static final String getB() { return b; } 
  public static final void setB(@NotNull String b) { ... } 
  @NotNull
  private static String b = "New Girl";
}

So the answer is, that you get a private static field, with static access methods to it (get and set)

Upvotes: 2

Related Questions