Kotlin : Public get private set var

ID : 20012

viewed : 14

Tags : kotlinkotlin

Top 5 Answer for Kotlin : Public get private set var

vote vote

91

var setterVisibility: String = "abc" // Initializer required, not a nullable type     private set // the setter is private and has the default implementation 

See: Properties Getter and Setter

vote vote

83

You can easily do it using the following approach:

var atmosphericPressure: Double = 760.0     get() = field     private set(value) {          field = value      } 

Look at this story on Medium: Property, Getter and Setter in Kotlin.

vote vote

70

vote vote

60

I know two obscure-ish things that make them different. Go me!

Firstly, there's the classic bug of making a delegate for each item in the list. If you use the foreach keyword, all your delegates can end up referring to the last item of the list:

    // A list of actions to execute later     List<Action> actions = new List<Action>();      // Numbers 0 to 9     List<int> numbers = Enumerable.Range(0, 10).ToList();      // Store an action that prints each number (WRONG!)     foreach (int number in numbers)         actions.Add(() => Console.WriteLine(number));      // Run the actions, we actually print 10 copies of "9"     foreach (Action action in actions)         action();      // So try again     actions.Clear();      // Store an action that prints each number (RIGHT!)     numbers.ForEach(number =>         actions.Add(() => Console.WriteLine(number)));      // Run the actions     foreach (Action action in actions)         action(); 

The List.ForEach method doesn't have this problem. The current item of the iteration is passed by value as an argument to the outer lambda, and then the inner lambda correctly captures that argument in its own closure. Problem solved.

(Sadly I believe ForEach is a member of List, rather than an extension method, though it's easy to define it yourself so you have this facility on any enumerable type.)

Secondly, the ForEach method approach has a limitation. If you are implementing IEnumerable by using yield return, you can't do a yield return inside the lambda. So looping through the items in a collection in order to yield return things is not possible by this method. You'll have to use the foreach keyword and work around the closure problem by manually making a copy of the current loop value inside the loop.

More here

vote vote

50

I guess the someList.ForEach() call could be easily parallelized whereas the normal foreach is not that easy to run parallel. You could easily run several different delegates on different cores, which is not that easy to do with a normal foreach.
Just my 2 cents

Top 3 video Explaining Kotlin : Public get private set var

Related QUESTION?