Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't get an access to a companion object's field

I'm wondering, why can't a class get an access to a companion object's field?

class MyClass {
  println(val1) // not found, why?
}

object MyClass {
  val val1 = "str"
}

It should, it should even have an access to the private fields of object MyClass.

like image 666
Incerteza Avatar asked Nov 20 '13 17:11

Incerteza


People also ask

How do you get the Kotlin companion object?

To create a companion object, you need to add the companion keyword in front of the object declaration. The output of the above code is “ You are calling me :) ” This is all about the companion object in Kotlin. Hope you liked the blog and will use the concept of companion in your Android application.

What is companion object in Android?

Answer: Companion object is not a Singleton object or Pattern in Kotlin – It's primarily used to define class level variables and methods called static variables. This is common across all instances of the class.

What is the point of a companion object?

A companion object is an object that's declared in the same file as a class , and has the same name as the class. A companion object and its class can access each other's private members. A companion object's apply method lets you create new instances of a class without using the new keyword.


1 Answers

You can do that by using MyClass.val1 instead of just val1. I guest that's done to denote that companion object members can be accessed from anywhere (with default modifiers).

like image 178
kompot Avatar answered Sep 17 '22 23:09

kompot