Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to override Java getter (method) with Kotlin val (property)?

Tags:

For example:

Java:

public class Foo {      public int getSomething() {         return 1;     }  } 

Kotlin:

class Bar : Foo() {      // works     override fun getSomething() = 2      // doesn't work ('something' overrides nothing)     // override val something = 2  } 

I thought that val something = 2 will be transformed to public int getSomething() { return 2; } in Java bytecode.

like image 277
Victor Avatar asked Nov 23 '17 11:11

Victor


People also ask

How do you override a method in Kotlin?

To override a method of the base class in the derived class, we use the override keyword followed by the fun keyword and the method name to be overridden.

Can we override variables in Kotlin?

Kotlin provides it by default. We can access the variables by just using the member variable names in it. It is not recommended to override any of the data class members like we used to do in Java. It is always recommended to use normal class if you want to override any of the class member at the runtime.


Video Answer


1 Answers

This seems to be a known issue here. Apparently it's a complicated matter and not likely to be resolved anytime soon.

The original response on the issue from Andrey Breslav:

This is a rather deep issue, unfortunately. It's unlikely that we'll ever make it work the way you'd like

Further down on the issue page you can see that it got even more complicated in regards to multiplatform projects.

like image 81
zsmb13 Avatar answered Sep 19 '22 17:09

zsmb13