Статические переменные в kotlin

Are static variables in Kotlin still part of instance objects

As we know to declare a variable static , we have to use companion object . A simple Example is listed below.

class MainActivity : AppCompatActivity() < companion object < val extraMessage = "message" >> 

This can be accessed in Other Activity as MainActivity.extraMessage , pretty neat and simple. However the document states , the syntax looks like its static but at runtime those are still instance members of real object. So is it like Kotlin does not have static members or Kotlin has just provided a simpler way to write the code.

2 Answers 2

In intelliJ you can have the kotlin plugin decompile the generated bytecode so you can see what is going on. Your code generates an approximation of the following code:

import kotlin.Metadata; import kotlin.jvm.internal.DefaultConstructorMarker; import org.jetbrains.annotations.NotNull; import android.support.v7.app.AppCompatActivity; @Metadata( mv = , bv = , k = 1, d1 = , d2 = ) public final class MainActivity extends AppCompatActivity < @NotNull private static final String extraMessage = "message"; public static final MainActivity.Companion Companion = new MainActivity.Companion((DefaultConstructorMarker)null); @Metadata( mv = , bv = , k = 1, d1 = , d2 = ) public static final class Companion < @NotNull public final String getExtraMessage() < return MainActivity.extraMessage; >private Companion() < >// $FF: synthetic method public Companion(DefaultConstructorMarker $constructor_marker) < this(); >> > 

Источник

How to create static variables and functions in Kotlin

In Kotlin, you have the const keyword that’s equal to the static keyword in Java.

The const keyword is used to create a variable that’s known to Kotlin before the compilation, so you don’t need to create an instance of a class to use it.

Читайте также:  HTML

The val keyword is used to create an immutable variable, just like the final keyword in java.

Combined together, the const val keyword allows you to create static variables in Kotlin object as follows:

The const val OBJ_DESCRIPTION above would be equal to final static String OBJ_DESCRIPTION in Java.

A static method can also be created in a Kotlin object just like creating a regular method:

  When you need to add static members to a class , however, you need to create a companion object inside the class and put the static members inside the object.

Here’s an example of a Kotlin class with static members:

   And that’s how you can create static variables and functions inside a Kotlin object or class types 😉

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Create and Use Static Variables in Kotlin

Create and Use Static Variables in Kotlin

  1. Declare Static Variables in Kotlin
  2. Use the Companion Object to Create Kotlin Static Variables
  3. Use the @JvmStatic Annotation to Create Kotlin Static Variables

When we declare a variable as static in Java, we can use it in different classes without the need for creating objects. It means that the memory of a static variable is allocated only once.

Since JVM does not allocate memory multiple times to a static variable, they are used for efficient memory management; however, there is no static keyword in Kotlin. So, how do we declare static variables in Kotlin?

This article introduces how we can implement the concept of static variables in Kotlin.

Declare Static Variables in Kotlin

We will go through both methods and see examples for implementing Kotlin static variables.

Use the Companion Object to Create Kotlin Static Variables

We can use the companion keyword to create a companion object to help achieve static variables functionality. We need to use the companion keyword before the object.

These objects can access the private members of a class; hence, there is no need to allocate the memory twice. We can use the class’s name to access these members.

Here’s an example of using the companion objects to achieve static functionality in Kotlin.

fun main(args: Array)   println("We are accessing a class variable without creating object.\n" + staticExample.privateVar) >  class staticExample  companion object   val privateVar = "Hi, you are accessing a static variable."  > > 

Use of companion object to create Kotlin static variables

Click here to check the demo of the example.

Use the @JvmStatic Annotation to Create Kotlin Static Variables

While the companion object members are like static variables in Java, they have a small difference. During the runtime, companion objects are still members of real objects; hence, they can also implement interfaces.

But one way to declare static variables in Kotlin is by using the @JvmStatic annotation. When we use the @JvmStatic annotation while declaring variables, JVM considers them actual static variables.

Here’s an example of using the @JvmStatic annotation to declare a variable.

fun main(args: Array)   println("We are accessing a class variable without creating object.\n" + staticExample.privateVar) >  object staticExample  @JvmStatic  val privateVar = "Hi, you are accessing a static variable." > 

Use of @JvmStatic annotation to create Kotlin static variables

Click here to check the demo of the example.

Kailash Vaviya is a freelance writer who started writing in 2019 and has never stopped since then as he fell in love with it. He has a soft corner for technology and likes to read, learn, and write about it. His content is focused on providing information to help build a brand presence and gain engagement.

Related Article — Kotlin Static

Источник

Русские Блоги

Статические переменные и статические методы в Котлин

Во время ежедневного процесса развития, Статическая переменная с Статический метод Это наше распространенное использование. Java считает, что все не незнакомы, то как использовать в Котлин? На самом деле, очень просто, только нужно включить переменные и методы companion object В домене, например, это:

Это очень просто после прочтения? Вы можете использовать его непосредственно в чистом Котлинском коде:

// инициализировать apikey каждой платформы PlatformConfig.setWeixin(Constant.WECHAT_APP_ID, Constant.WECHAT_APP_SECRET) PlatformConfig.setSinaWeibo(Constant.WEIBO_APP_KEY, Constant.WEIBO_SECRET, Constant.WEIBO_AUTH_RETURN_URL) 

Однако, если мы используем Java и Kotlin Hybrid Development, он не может пройти в код Java Статическая переменная Способ использования статических переменных или методов, но передает следующее:

// инициализировать apikey каждой платформы PlatformConfig.setWeixin(Constant.Companion.WECHAT_APP_ID, Constant.WECHAT_APP_SECRET) PlatformConfig.setSinaWeibo(Constant.Companion.WEIBO_APP_KEY, Constant.WEIBO_SECRET, Constant.WEIBO_AUTH_RETURN_URL) 

Если мы представляем, что Котлин напрямую проходит Имя класса. Статическая переменная Что используется в режиме? Мы можем использовать аннотации @JvmField с @JvmStatic Чтобы пометить статические переменные и статические методы, я могу использовать статические элементы напрямую, как код Java! Например, это:

/** * @author moosphon on 2018/12/12 * Desc: равномерные обработчики */ class ExceptionHandler < companion object < @JvmField var errorCode = NetRequestStatus.UNKNOWN_ERROR @JvmField Var errormessage = "запрос не удался, попробуйте позже" @JvmStatic fun handleException(e : Throwable): String< e.printStackTrace() when(e)< is SocketException -> < Logger.e («ExceptionHandler», «Исключение сетевого подключения:» + E.Message) errorCode = NetRequestStatus.NETWORK_ERROR Errormessage = "Исключение сетевого подключения" >is JsonParseException -> < Logger.e («ExceptionHandler», «Аналитическое исключение данных:» + E.Message) errorCode = NetRequestStatus.PARSE_ERROR Errormessage = "Данные аналитические ненормальные" >else -> < try < Logger.e ("ExceptionHandler", "Другая ошибка: + e.message) >catch (e1: Exception) < Logger.e ("ExceptionHandler", "Неизвестная ошибка:" + e.message) >errorCode = NetRequestStatus.UNKNOWN_ERROR Errormessage = "Неизвестные ошибки, молись вместе, поправляйтесь ~" > > return errorMessage > > > 

Это относительно занято еще несколько раз, и будет продолжать приносить вам артикул Kotlin, вы будете ждать и посмотреть. Android-Kotlin Exchange Группа: 601924443

Источник

Оцените статью