Scope of methods of an anonymous object - Kotlin - kotlin

In Kotlin if I define a method on an anonymous object, sometimes I am able to access it, while other times I am not. This seems to have something to do with scoping rules, but I am not sure what.
In the code example below, the access to example3.field.method() will cause a compilation error. Interestingly, example2.field.method() compiles just fine.
What could be the explanation for the below behaviour?
class Example3 {
val field = object {
fun method() {}
}
}
fun showcase() {
val example1 = object {
fun method() {}
}
example1.method()
println(example1::class.qualifiedName)
class Example2 {
val field = object {
fun method() {}
}
}
val example2 = Example2()
example2.field.method()
println(example2::class.qualifiedName)
val example3 = Example3()
// example3.field.method() // won't compile
println(example3::class.qualifiedName)
}

From docs Object Expressions and Declarations:
Note that anonymous objects can be used as types only in local and
private declarations. If you use an anonymous object as a return type
of a public function or the type of a public property, the actual type
of that function or property will be the declared supertype of the
anonymous object, or Any if you didn't declare any supertype. Members
added in the anonymous object will not be accessible.
Demonstrated in code sample below:
class Example4{
val publicObj = object{
val x = 1
}
private val privateObj = object{
val x = 2
}
fun showcase(){
val scopedObj = object{
val x = 3
}
println(publicObj.x) // ERROR : unresolved reference: x
println(privateObj.x) // OK
println(scopedObj.x) // OK
}
}

Pawel gave the correct answer to your question, pointing to the documentation:
the actual type of that function or property will be the declared supertype of the anonymous object, or Any if you didn't declare any supertype.
But just adding that if you really need to access example3.field.method() you could declare a supertype to field in Example3:
interface MyInterface {
fun method()
}
class Example3 {
val field = object: MyInterface {
override fun method() {}
}
}
fun main() {
val example3 = Example3()
example3.field.method()
}

Related

I have a question about generic in kotlin

I got an error. Like this :
Error 1 : Platform declaration clash: The following declarations have the same JVM signature (getData()Ljava/lang/Object;):
fun (): I defined in typeErasure2
fun getData(): I defined in typeErasure2
Error 2 : Platform declaration clash: The following declarations have the same JVM signature (getData()Ljava/lang/Object;):
fun (): I defined in typeErasure2
fun getData(): I defined in typeErasure2
fun main(args : Array<String>){
var te = typeErasure("Jennie")
println(te.getData())
var te2 = typeErasure2("Sam")
println(te2.getData())
}
class typeErasure<I>(name : I){
private val data : I = name
fun getData() : I = data
}
class typeErasure2<I>(name : I){
val data : I = name // error 1
fun getData() : I = data // error 2
}
when I use the private keyword the program can run, otherwise it will get an error. anyone can explain to me? :)
This has nothing to do with generics. The problem with your code is that
public fun getData(): I
Is an accesor for "data". But when "data" is a public field, then the accesor is redundant. So when you do:
val someValue = myObject.data
Then the compiler cannot tell if it should use the accessor getData() or it should just point to the field directly.
When getData is private, then the compiler clearly knows that it can't use it so then it will point to the field directly.
class typeErasure2<I>(name : I){
val data : I = name
fun getData() : I = data
}
fun main() {
val obj = typeErasure2<Int>(123)
println(obj.data) // <--- Ask yourself, what does this line do exactly?
}
class typeErasure2<I>(name : I){
val data : I = name
private fun getData() : I = data
}
fun main() {
val obj = typeErasure2<Int>(123)
println(obj.data) // <--- Here it is clear
// it is not the "getData" because that one is private,
// so it must be the public field "data" you are pointing to
}
Kotlin's logic of properties differ slightly from Java's fields.
Whenever you declare any variable in class, its getter and setters are automatically generated, and they can be customized with get() or set {} after it.
Declaring getVariable() manually will result in platform clash, as getter is already defined for the field in the variable declaration and you are creating function with the same name as well.
You can use #JvmField annotation to instruct the compiler to not generate any getter or setter for the field.
#JvmField
val data: I = name
fun getData(): I = data

what is default value type of kotlin class constructor parameter?

class Greeter(name: String) {
fun greet() {
println("Hello, $name")
}
}
fun main(args: Array<String>) {
Greeter(args[0]).greet()
}
for above program I got this error
Unresolved reference: name
but when I add var or val
class Greeter(var name: String) {
or
class Greeter(val name: String) {
then program works fine, so why I need to add var or val to name, what is default type for constructor parameter val or var and why program gives me error when I not mention var or val
To use your value in the constructor like class Greeter(name: String), you can use init{}
class Greeter(name: String) {
var string:name = ""
init{
this.name = name
}
fun greet() {
println("Hello, $name")
}
}
or If you use val or var in the constructor it is more like class level variable and can be accessed anywhere inside the class
class Greeter(var name:String){
fun greet() {
println("Hello, $name")
}
}
The variable name can be used directly in the class then.
We can also give default values for the variables in both cases.
Adding val or var makes the parameter a property and can be accessed in the whole class.
Without this, it is only accessible inside init{}
The question is not making any sense, But the problem you are facing does make sense. In your case, the approach you are using is,
Wrong-Way:
// here name is just a dependency/value which will be used by the Greeter
// but since it is not assigned to any class members,
// it will not be accessible for member methods
class Greeter(name: String) {
fun greet(){} // can not access the 'name' value
}
Right-Way:
// here name is passed as a parameter but it is also made a class member
// with the same name, this class member will immutable as it is declared as 'val'
class Greeter(val name: String) {
fun greet(){} // can access the 'name' value
}
You can also replace val with var to make the name a mutable class member.

Overload resolution ambiguity. All these functions match

I tried to check, lateinit variable is initialized or not in a function using reference operator. The function name and variable name is same in this case. So that Kotlin throws
Overload resolution ambiguity. All these functions match
exception. Actually what's wrong in this code?
class ABC
class MyClass {
private lateinit var abc: ABC
fun abc() {
if(!::abc.isInitialized){
println("Hello")
}
}
}
It's a simple name clash. The compiler does not know whether you're referring to the method abc or the property abc. A renaming fixes the problem:
class MyClass {
private lateinit var abc: ABC
fun abcFun() {
val prop = this::abc
if (!::abc.isInitialized) {
println("Hello")
}
}
}
You can disambiguate the reference by extracting a variable and explicitly specifying its type:
class ABC
class MyClass {
private lateinit var abc: ABC
fun abc() {
val abc: KProperty0<ABC> = ::abc
if(!abc.isInitialized){
println("Hello")
}
}
}
The issue is that you have a property called abc, which can be accessed by calling the Kotlin property accessor this.abc (sort of "getter") and you define another method with the same name, so it doesn't recognize which one to reference with syntax ::abc.
This is also stated by the error message from the IDE:
Overload resolution ambiguity. All these functions match:
private final lateinit var abc: ABC defined in MyClass
public final fun abc(): Unit defined in MyClass
If you would access the function abc or the property abc on an instance of MyClass without the reference syntax, it would actually work, although I would not recommend it. See here:
class ABC
class MyClass{
private lateinit var abc: ABC
fun abc(){
abc
}
}
fun main(args: Array<String>) {
val c = MyClass()
c.abc()
}
This code compiles without any problems.
But this is not what you want. Create a backing field _abc and access it via a property without backing field abc. This way you can return a default instance of ABC, if _abc has not been initialized.
class MyClass {
private lateinit var _abc: ABC
val abc: ABC get() {
if(!::_abc.isInitialized){
println("Uninitialized")
return ABC() // some default instance
}
println("Initialized")
return _abc
}
fun initABC() {
_abc = ABC()
}
}
fun main(args: Array<String>) {
val c = MyClass()
c.abc
c.initABC()
c.abc
}
Output:
Uninitialized
Initialized

What are the advantages of a companion object over a plain object?

Kotlin code like this:
class Foo {
companion object {
fun a() : Int = 1
}
fun b() = a() + 1
}
can trivially be changed to
object FooStatic {
fun a() : Int = 1
}
class Foo {
fun b() = FooStatic.a()
}
I'm aware that the companion object can be used to allow use as real java static function, but are there any other advantages to using the companion object?
One of the key differences is visibility of the members.
In a companion object, visibility to the containing class is as-if the members were part of the class - this is not the case for a raw object.
The example below shows that you cant use an "object" to implement private static internals of a class.
package com.example
class Boo {
companion object Boo_Core {
// Public "static" call that non-Boo classes should not be able to call
fun add_pub(a:Int) = a+1;
// Internal "static" call that non-Boo classes should not be able to call
private fun add_priv(a:Int) = a+1;
}
// OK: Functions in Boo can call the public members of the companion object
fun blah_pub(a:Int) = add_pub(a)
// OK: Functions in Boo can call the private members of the companion object
fun blah_priv(a:Int) = add_priv(a)
}
//Same idea as the companion object, but as an "object" instead.
object Foo_Core {
fun add_pub(a:Int) = a+1
private fun add_priv(a:Int) = a+1;
}
class Foo {
// OK Foo can get Foo_Cors add_pub
fun blah_pub(a:Int) = Foo_Core.add_pub(a);
// ERROR: can not get to add_priv
// fun blah_priv(a:Int) = Foo_Core.add_priv(a);
}
class AnInterloper {
// OK Other classes can use public entries in Foo.
fun blah_foo_pub(a:Int) = Foo_Core.add_pub(a);
// ERROR Other classes can use public entries in Foo.
// fun blah_foo_priv(a:Int) = Foo_Core.add_priv(a);
// OK: Other classes can use public Boo classes
fun blah_boo_pub(a:Int) = Boo.add_pub(a);
// ERROR: Other classes can not use private Boo classes
// fun blah_boo_priv(a:Int) = Boo.add_priv(a);
}

Function returning ad-hoc object in Kotlin

Currently I have a private function which returns a Pair<User, User> object. The first user is the sender of something, the second user is the receiver of that thing.
I think this Pair<User, User> is not enough self explanatory - or clean if you like - even though it's just a private function.
Is it possible to return with an ad-hoc object like this:
private fun findUsers(instanceWrapper: ExceptionInstanceWrapper): Any {
return object {
val sender = userCrud.findOne(instanceWrapper.fromWho)
val receiver = userCrud.findOne(instanceWrapper.toWho)
}
}
and use the returned value like this:
// ...
val users = findUsers(instanceWrapper)
users.sender // ...
users.receiver // ...
// ...
?
If not, what's the point of ad-hoc object in Kotlin?
Since the type can not be denoted in the language, use return type inference:
class Example {
private fun findUsers(instanceWrapper: ExceptionInstanceWrapper) =
object {
val sender = userCrud.findOne(instanceWrapper.fromWho)
val receiver = userCrud.findOne(instanceWrapper.toWho)
}
fun foo() = findUsers(ExceptionInstanceWrapper()).sender
}
Another option would be to devise a data class:
class Example {
private data class Users(val sender: User, val receiver: User)
private fun findUsers(instanceWrapper: ExceptionInstanceWrapper): Users {
return Users(
sender = userCrud.findOne(instanceWrapper.fromWho),
receiver = userCrud.findOne(instanceWrapper.toWho)
)
}
fun foo() = findUsers(ExceptionInstanceWrapper()).sender
}
Simply define your function as a lambda.
Here's simple object I've just written as an example in another context:
private val Map = {
val data = IntArray(400)
for (index in data.indices) {
data[index] = index * 3
}
object {
val get = { x: Int, y: Int ->
data[y * 20 + x]
}
}
}
fun main() {
val map = Map()
println(map.get(12,1))
}
Unfortunately, you cannot assign a type name, so it can be used as a return value but not as an argument. Maybe they'll make this possible so we can finally do OOP JS style.
Alternatively, they could implement object types equivalent to function types but that could end up being too wordy. You could then do a typedef but that would actually just be a kind of class definition 😅
Another option is to have a generic class for return types:
data class OutVal<T>(private var v: T?) {
fun set(newVal: T) {
v = newVal
}
fun get() = v
}
Usage example:
private fun findUsers(instanceWrapper: ExceptionInstanceWrapper,
sender: OutVal<String>, receiver: OutVal<String>) {
sender.set(userCrud.findOne(instanceWrapper.fromWho))
receiver.set(userCrud.findOne(instanceWrapper.toWho))
}
val sender = OutVal("")
val receiver = OutVal("")
findUsers(instanceWrapper, sender, receiver)
sender.get() // ...
receiver.get() // ...