Day 4 of #30DaysofKotlin

classes and objects.

So far we covered variable functions,loops and a few more topics. For previous post see, Day3 and Day2.

Today, we’ll see filters , classes and objects in kotlin.

filters can be applied on a list to get the elements that fulfils our requirement.

We have a list named party, now we only want to print the element starting with ‘d’ ,we can easily do this using filters. Let’s see how,

“DJ” will not be printed as we only applied filter for small case d.

Let’s see another example: here we are iterating through the list.We first multiply every integer with 2,then filter out those divisible by 3.

we can also iterate using index,by using filterIndexed(). It takes 2 arguments,index and the element.

here, we are getting only those elements whose index is less than 2.

Filters are of two types ,eager and lazy.In eager filters ,the result list created immediately,when the filter is used.Whereas lazy filters create result when they are accessed during runtime.

kotlin filters are eager by default,but they can be changed to lazy by using Sequence,

The filtered variable doesn’t hold a new list—it'll hold a Sequence of the list elements and knowledge of the filter to apply to those elements. the filter is applied,Whenever we access elements of the Sequence.

Classes and Objects

By definition,Classes are blueprints for objects and Objects are instances of classes.

In simpler words,class is a collection of data and functions called methods ,and objects are something we need to use the data and methods of that class.

The class declaration consist of class name, class header and class body enclosed with curly braces.

we created a class which has 3 variables,which are integers.

now we’ll create a method which prints the value of all three variables we defined.

To create an object inside main function , we use class name followed by object name or by calling constructor, and to access the member function, we use object_name.method_name():

A constructor is a function that is called when an object is created. If we want to provide a constructor, we need to write keyword constructor just after the class name or we can simply add arguments to class in its declaration,like we did in following code:

here we provided default values for the variables so we can create an object without arguments,however we can change the values if we want by passing them to the constructor.

we created a function named arrangeParty to create class object, and call class method.

init blocks

If the constructor needs more initialisation code, it can be placed in one or more init blocks.

init blocks are executed in sequence in which they appear in the class definition.

That’s it!!

Today we learnt

  1. filters
  2. classes
  3. objects and constructors
  4. init blocks

There’s a lot more to classes and objects, that we’ll see tomorrow!

hope you are enjoying this series, Keep practising!!

just a learner.