Press enter to see results or esc to cancel.

Lesson 32: OOP – Named Object in kotlin language

()

Another feature of the Kotlin language is to be able to define an object immediately without having to declare a class.

A new object keyword appears with which we can create these objects directly.

Problem 1

Define an object called Math with a property that stores the PI value and a method that returns a random value in a certain range.

Project134 – Principal.kt

``````object Matematics {
val PI = 3.1416
fun random (min: Int, max: Int) = ((Math.random () * (max + 1 - min)) + min) .toInt ()
}

fun main (parameter: Array <String>) {
println ("The value of Pi is \${Matematics.PI}")
print ("A random value between 5 and 10:")
println (Matematics.random (5, 10))
}``````

To define an object without having to declare a class, we use the keyword object and then the object name that we are going to create, then between braces we define its properties and methods (in our example we define a property and a method):

```Object Matematics{
Val PI = 3.1416
(Minimum: Int, max: Int) = ((Math.random () * (max + 1 - minimum)) + minimum) .toInt ()
}
```

To access the property or method defined in the Mathematical object we do it by preceding the name of the object to the method or property that we have to call:

```Fun main (parameter: Array <String>) {
Println ("The value of Pi is \$ {Math.PI}")
Print ("A random value between 5 and 10:")
Println (Matematics.alternative (5, 10))
}
```

Local objects to a function or method.

To be able to define named objects that are not global as the previous case but are defined within a function we must do it by defining a local variable and an anonymous object (ie without name)

Problem 2

Create a local object in the main function that lets you throw 5 dice and store those values in an array. Define a property that stores 5 integers and 3 methods: one that loads the 5 array elements with random values between 1 and 6, one that prints the array, and finally one that returns the highest array value.

Project135 – Principal.kt

``````fun main (parameter: Array <String>) {
val data = object {
val array = IntArray (5)
fun generate () {
for (i in array.indices)
array [i] = ((Math.random () * 6) + 1) .toInt ()
}

fun print () {
for (element in array)
print ("\$element -")
println ();
}

fun major (): Int {
var may = array [0]
for (i in array.indices)
if (array [i] > may)
may = array [i]
return may
}
}

data.generate ()
data.print ()
print ("Highest value:")
println (data.major())
}``````

To define a local object a function must be anonymous, ie we do not have a name after the keyword object.
What we must do is to assign the value returned by object to a variable:

```    Val data = object {
```

Within the object keys we define the properties and implement their methods:

```        Fun generate () {
For (i in array.indices)
Array [i] = ((Math.random () * 6) + 1) .toInt ()
}

Fun print () {
For (element in array)
Print ("\$element -")
Println();
}

Fun major (): Int {
Var may = array [0]
For (i in array.indices)
If (array [i]> may)
May = array [i]
Return may
}
}
```

Then we can access the properties and their methods by preceding the name of the variable that is loaded when calling object:

```Data.generate ()
Data.print ()
Print ("Highest value:")
println (data.major())```

Proposed problem

• Define a named object:
```Object Major {
```

With three methods called “max” with two parameters each. The methods differ in that one receives Int data types, another of Float types, and finally the latter receives Double data types. All three methods must return the greater of the two data they receive.

```Solution
[sociallocker id="958"]
```
``````object major {
fun max (x1: Int, x2: Int) = if (x1> x2) x1 else x2

fun  max (x1: Float, x2: Float) = if (x1> x2) x1 else x2

fun max (x1: Double, x2: Double) = if (x1> x2) x1 else x2
}

fun main (parameter: Array <String>) {
println (major.max (4, 5))
println (major.max (10.2f, 23.5f))
println (major.max (4.5, 5.2))
}

[/sociallocker]``````

Click on a star to rate it!

Average rating / 5. Vote count:

Be the first to rate this post.!

As you found this post useful...