Kotlin中的静态变量? [英] Static variables in kotlin?

查看:77
本文介绍了Kotlin中的静态变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要定义一个变量并将其访问,就像Java中的静态变量一样.我只想通过类名来访问此变量.

I need to define a variable and acces it like static variables in java. I want to acces this variable just by name of a class.

推荐答案

将其放在您班级的同伴对象内

Put it inside of a companion object in your class

class Example {
    companion object { 
          val foo = 1
     }
}

Example.foo

如果类中的所有内容都是静态的,则可以将该类作为Kotlin中的对象

If everything inside of your class is going to be static then you can make that class an object in Kotlin

object Example {

        val foo = 1
 }

Example.foo

这篇关于Kotlin中的静态变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆