Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I put the { of an anonymous class at a new line in Kotlin?

Tags:

kotlin

This question may be stupid but... why? Personally I like the Microsoft style where { is at the same column as the matching }. In all languages I have used, it did not matter where { was placed.

But in Kotlin, only this works.

image_view.viewTreeObserver.addOnGlobalLayoutListener{
};

And this causes an error.

image_view.viewTreeObserver.addOnGlobalLayoutListener
{
};
like image 932
Damn Vegetables Avatar asked Nov 22 '17 19:11

Damn Vegetables


People also ask

How do I write an anonymous class on Kotlin?

In kotlin, we can achieve this by using the “Object” keyword; the object declaration contains properties, methods, and so on. However, mainly it does not allowed the constructor to create the object. Like that object, a keyword is used for to create the objects of the anonymous class known as the anonymous object.

Can anonymous classes have constructor?

Since anonymous inner class has no name, an anonymous inner class cannot have an explicit constructor in Java.

How do you call an anonymous window constructor?

Object a = new Class1(){ void someNewMethod(){ } public XXXXXXXX(int a){ super(); System. out. println(a); } };


1 Answers

https://kotlinlang.org/docs/reference/grammar.html#semicolons

Because your second example has the same meaning as

image_view.viewTreeObserver.addOnGlobalLayoutListener;
{
};

a property access followed by an empty lambda.

like image 112
ephemient Avatar answered Oct 27 '22 14:10

ephemient