Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to a custom getter in kotlin

Tags:

kotlin

I have been reading about properties in Kotlin, including custom getters and setters.

However, I was wondering if it is possible to create a custom getter with extra parameters.

For example, consider the following method in Java:

public String getDisplayedValue(Context context) {
    if (PrefUtils.useImperialUnits(context)) {
        // return stuff
    } else {
        // return other stuff
    }
}

Note that the static method in PrefUtils has to have Context as a parameter, so removing this is not an option.

I would like to write it like this in Kotlin:

val displayedValue: String
    get(context: Context) {
        return if (PrefUtils.useImperialUnits(context)) {
            // stuff
        } else {
            // other stuff
        }
    }

But my IDE highlights all of this in red.

I am aware I can create a function in my class to get the displayed value, but this would mean I would have to use .getDisplayedValue(Context) in Kotlin as well instead of being able to refer to the property by name as in .displayedValue.

Is there a way to create a custom getter like this?

EDIT: If not, would it be best to write a function for this, or to pass Context into the parameters of the class constructor?

like image 392
Farbod Salamat-Zadeh Avatar asked Jul 31 '16 13:07

Farbod Salamat-Zadeh


People also ask

How do you pass a parameter to a function in Kotlin?

In Kotlin, You can pass a variable number of arguments to a function by declaring the function with a vararg parameter. a vararg parameter of type T is internally represented as an array of type T ( Array<T> ) inside the function body.

How do you make a Kotlin setter getter?

In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'. The data type of 'name' is String and we shall initialize it with some default value.

What is private VAR in Kotlin?

In Kotlin, private modifiers allow only the code declared inside the same scope, access. It does not allow access to the modifier variable or function outside the scope.

What are Kotlin's properties?

Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword. By default, all properties and functions in Kotlin are public.


1 Answers

As far as I know, property getter cannot have parameter. Write a function instead.

like image 56
Szörényi Ádám Avatar answered Oct 02 '22 08:10

Szörényi Ádám