'How to make multiple constructors in Kotlin?
I want to use library which is in Java and it has alot of errors so I'm trying to change it to Kotlin. And AndroidStudio is not converting Java to Kotlin properly so I have to do it function by function and check it manually. But these 3 constructors gives error:
Error: None of these following functions can be called with the arguments supplied
Java:
public class CountryCodePicker extends RelativeLayout
...
public CountryCodePicker(Context context) {
super(context);
if (!isInEditMode()) init(null);
}
public CountryCodePicker(Context context, AttributeSet attrs) {
super(context, attrs);
if (!isInEditMode()) init(attrs);
}
public CountryCodePicker(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (!isInEditMode()) init(attrs);
}
Kotlin:
class CountryCodePicker: RelativeLayout
...
constructor(context: Context): this{
super(context)
if (!isInEditMode) init(null)
}
constructor(context: Context, attrs: AttributeSet): this{
super(context, attrs)
if (!isInEditMode) init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): this{
super(context, attrs, defStyleAttr)
if (!isInEditMode) init(attrs)
}
Solution 1:[1]
class CountryCodePicker: RelativeLayout {
constructor(context: Context) : super(context) {
if (!isInEditMode) init(null)
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs){
if (!isInEditMode) init(attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int): super(context, attrs, defStyleAttr) {
if (!isInEditMode) init(attrs)
}
}
Solution 2:[2]
You should use JvmOverloads
for this:
class CountryCodePicker @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
init {
if (!isInEditMode()) {
init(attrs) // or better inline the function body
}
}
}
The JvmOverloads
will create the 3 constructors with the default values as defined. That is the behavior you would expect and makes the code cleaner.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Rahul Sharma |
Solution 2 | rekire |