In Java I can declare this
private List a;
//onCreate
a = new ArrayList()
But in Kotlin it shows error, it forces me to specific a type
private List<String> a
Sometimes I do not want to provide a type ( I do not need to) but it shows error in Kotlin For example In Java
public abstract class BaseActivity<T extends ViewDataBinding> extends AppCompatActivity {
//something
}
public abstract class BaseFragment {
private BaseActivity activity;
//something
}
//in kotkin I can't write
lateinit var activity: BaseAtivity //show error here (I have to specific a type but this is the base class and I do not want to specific a type here). I just want a reference of BaseActivity
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof BaseActivity) { //good in java but show error
//in kotlin because I have to //specific a type like BaseAtivity<something>
BaseActivity activity = (BaseActivity) context;
this.mActivity = activity;
activity.onFragmentAttached();
}
}
What can I write in Kotlin to achieve the same code in java
In Kotlin, we use val to declare an immutable variable and var to declare a mutable variable. You can also optionally specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.
To declare a string in Kotlin, we need to use double quotes(” “), single quotes are not allowed to define Strings. Creating an empty String: To create an empty string in Kotlin, we need to create an instance of String class.
To create an empty String in Kotlin, assign the variable with empty double quotes "" , or with String class constructor String() .
A raw type is the name of a generic class or interface without any type arguments.
You can use star projections
e.g.
private List<*> a
Well, technically the star projection isn't the raw type. The raw types are not supported by Kotlin. You cannot define a variable of raw type, nor can you define a method param of raw type. It won't compile.
And if you use the star projection, there's little help i it since there's not much you can do with it. So you will end up casting it to a type you need, cross your fingers and hope for the best. Best is to avoid java API with raw types.
Or create your own variable of that generic class and safely transfer all the information to it. If it's a Collection, then iterate through it and put elements into new Collection. it will save you from null pointer exception too since the elements or the collection itself can be null.
By the way, in your example there are some serious design flaws.
(BaseActivity<*>getActivity())
or you create a memory leak. <*> for Kotlin, <?> for Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With