Anonymous class in kotlin

Вложенные и внутренние классы Kotlin

В этом руководстве мы рассмотрим четыре способа создания вложенных и внутренних классов вKotlin.

2. Быстрое сравнение с Java

Для тех, кто думает оJava nested classes, давайте сделаем краткое изложение связанных терминов:

Нестатические вложенные классы

Статические вложенные классы

Хотя, конечно, они не идентичны, мы можем использовать эту таблицу в качестве руководства при рассмотрении возможностей и вариантов использования для каждого из них.

3. Внутренние классы

First, we can declare a class inside another class using the keyword inner.

Эти классыhave access to members of the enclosing class, even private members.

Чтобы использовать его, нам нужно сначала создать экземпляр внешнего класса; без него мы не сможем использовать внутренние классы.

Давайте создадим внутренний классHardDisk внутри классаComputer:

class Computer(val model: String) < inner class HardDisk(val sizeInGb: Int) < fun getInfo() = "Installed on $<[email protected]>with $sizeInGb GB" > >

Обратите внимание, что мы используемqualified this expression для доступа к членам классаComputer, что аналогично тому, как мы делаемComputer.this в Java-эквивалентеHardDisk.

Теперь давайте посмотрим, как это работает:

@Test fun givenHardDisk_whenGetInfo_thenGetComputerModelAndDiskSizeInGb()

4. Местные Внутренние Классы

Next, we can define a class inside a method’s body or in a scope block.

Давайте сделаем небольшой пример, чтобы увидеть, как это работает.

Во-первых, давайте определим методpowerOn для нашего классаComputer:

Внутри методаpowerOn объявим классLed и заставим его мигать:

fun powerOn(): String < class Led(val color: String) < fun blink(): String < return "blinking $color" >> val powerLed = Led("Green") return powerLed.blink() >

Обратите внимание, что область действия классаLed находится только внутри метода.

With local inner classes, we can access and modify variables declared in the outer scope. ДобавимdefaultColor в методpowerOn:

Теперь давайте добавимchangeDefaultPowerOnColor в наш классLed:

class Led(val color: String) < //. fun changeDefaultPowerOnColor() < defaultColor = "Violet" >> val powerLed = Led("Green") log.debug("defaultColor is $defaultColor") powerLed.changeDefaultPowerOnColor() log.debug("defaultColor changed inside Led " + "class to $defaultColor")
[main] DEBUG c.b.n.Computer - defaultColor is Blue [main] DEBUG c.b.n.Computer - defaultColor changed inside Led class to Violet

5. Анонимные объекты

Anonymous objects can be used to define an implementation of an interface or an abstract class without creating a reusable implementation.

Большая разница между анонимными объектами в Kotlin и анонимными внутренними классами в Java заключается в том, чтоanonymous objects can implement multiple interfaces and methods.

Во-первых, давайте добавим интерфейсSwitcher в наш классComputer:

Теперь давайте добавим реализацию этого интерфейса внутри методаpowerOn:

fun powerOn(): String < //. val powerSwitch = object : Switcher < override fun on(): String < return powerLed.blink() >> return powerSwitch.on() >

Как мы видим, для определения нашего анонимного объектаpowerSwitch мы используемobject expression. Кроме того, мы должны учитывать, что каждый раз, когда вызывается выражение объекта, создается новый экземпляр объекта.

С помощью анонимных объектов, таких как внутренние классы, мы можем изменять переменные, ранее объявленные в области видимости. Это потому, что Kotlin не имеет эффективного последнего ограничения, которого мы ожидаем от Java.

Теперь давайте добавимchangeDefaultPowerOnColor в наш объектPowerSwitch и назовем его:

val powerSwitch = object : Switcher < //. fun changeDefaultPowerOnColor() < defaultColor = "Yellow" >> powerSwitch.changeDefaultPowerOnColor() log.debug("defaultColor changed inside powerSwitch " + "anonymous object to $defaultColor")

Мы увидим такой результат:

. [main] DEBUG c.b.n.Computer - defaultColor changed inside powerSwitch anonymous object to Yellow

Также обратите внимание, что если наш объект является экземпляром интерфейса или класса с одним абстрактным методом; мы можем создать его, используяlambda expression.

6. Вложенные классы

И наконец,we can define a class inside another class without the keyword inner:

class Computer(val model: String)

In this type of class, we don’t have access to the outer class instance. Но мы можем получить доступ кcompanion object членам включающего класса.

Итак, давайте определимcompanion object внутри нашего классаComputer, чтобы увидеть его:

А затем метод внутриMotherBoard для получения информации о нем и внешнем классе:

fun getInfo() = "Made by $manufacturer - $originCountry - $"

Теперь мы можем проверить это, чтобы увидеть, как это работает:

@Test fun givenMotherboard_whenGetInfo_thenGetInstalledAndBuiltDetails()

Как видим, мы создаемmotherBoard без экземпляра классаComputer.

7. Заключение

В этой статье мы увидели, как определять и использовать вложенные и внутренние классы в Kotlin, чтобы сделать наш код более кратким и инкапсулированным.

Кроме того, мы заметили некоторое сходство с соответствующими концепциями Java.

Полностью рабочий пример для этого руководства можно найтиover on GitHub.

Источник

Kotlin anonymous class

Kotlin anonymous class

The kotlin anonymous class is one of the features, and it is the local classes which except that they do not have the name by using object expressions we can create the objects of the anonymous class that is, the classes that have not been explicitly declared with the class also such classes are handy for one-time use we can define it from the scratch that can be inherited from the existing classes or implement with the interfaces the instance of the anonymous class are also defined as the anonymous object since it’s an expression it is not considered to be the name of the class.

Web development, programming languages, Software testing & others

Syntax of Kotlin anonymous class

In kotlin language, we used classes, sealed class, kclass, data class, etc. These are the same type of classes handled by the kotlin for each of its has its own syntax and attributes for implementing the application.

open class name() < ---some codes depends on the requirement--- >fun main(args:Array)
interface name < fun names() >fun main(args:Arrays) < var n:name=object:name < override fun names() < --some codes— >> n.names() >

The above codes are the basic syntax for creating the anonymous class in different ways like we create with the help of an open class name() and interface name. We can achieve the anonymous class in kotlin with the above ways.

How anonymous class Works in Kotlin?

  • The anonymous class is one of the features and concepts for the kotlin language. It is used to create the class instance by using the object expression. The object declarations are one of the singleton object patterns where the class can have only one instance; it is more useful for to working the backend like databases etc. In kotlin, we can achieve this by using the “Object” keyword; the object declaration contains properties, methods, and so on. However, mainly it does not allowed the constructor to create the object.
  • Like that object, a keyword is used for to create the objects of the anonymous class known as the anonymous object. They are used to create the object if it needed a slight modification of the same class or interface without declaring the subclass in the kotlin. For example, if suppose we are implementing the class with a separate constructor to declare the anonymous object, we need to pass the appropriate constructor and parameters while calling the method in the main.
  • The anonymous class and object are also achieved by using the interface; we can create the interface with some methods. The interface does not have a body, so we can create the object of the interface by using the object keyword, so the anonymous object is created at the time. Then, with the help of its reference, we can call the methods.

Examples of Kotlin anonymous class

Different examples are mentioned below:

Example #1

package one; open class Department(empname: String, id: Int) < init < println("empname: $empname, id: $id") >fun IT() = println("Welcome To My Domain and welcome to Our IT department.") fun Accounts() = println("Welcome To My Domain and welcome to Our Accounts department.") fun Finance() = println("Welcome To My Domain and welcome to Our Finance department.") fun Support() = println("Welcome To My Domain and welcome to Our Support department.") fun Management() = println("Welcome To My Domain and welcome to Our Management department.") fun Security() = println("Welcome To My Domain and welcome to Our Security department.") fun QA() = println("Welcome To My Domain and welcome to Our QA department.") fun Development() = println("Welcome To My Domain and welcome to Our Development department.") fun Document() = println("Welcome To My Domain and welcome to Our Document department.") fun Hosting() = println("Welcome To My Domain and welcome to Our Hosting department.") open fun HR() = println("Welcome To My Domain and welcome to Our HR department.") > fun main(args: Array) < val vars = object : Department("siva", 41) < override fun HR() = println("I dont have the HR. I am an contract employee from the vendor.") >vars.IT() vars.Accounts() vars.Finance() vars.Support() vars.Management() vars.Security() vars.QA() vars.Development() vars.Document() vars.Hosting() vars.HR() >

Kotlin Anonymous class 1

In the above example, we used class for to create the anonymous object in the main method. With the help of its variable reference, we can call the interface method, which is overrided.

Example #2

package one; interface MainDetails < fun Empdetail1() < val id:Int=41 var name:String="Arun" >fun Empdetail2() < val id:Int=43 var name:String="Raman" >fun Empdetail3() < val id:Int=44 var name:String="Kumar" >> fun main(args:Array) < var n:MainDetails=object:MainDetails < override fun Empdetail1() < val id:Int=42 var name:String="Sivaraman" println("Welcome To My Domain its the second example that related to the kotlin anonymous class $name,$id") >override fun Empdetail2() < val id:Int=45 var name:String="Arun kumar" println("Welcome To My Domain its the second example that related to the kotlin anonymous class $name,$id") >override fun Empdetail3() < val id:Int=46 var name:String="Bala murali" println("Welcome To My Domain its the second example that related to the kotlin anonymous class $name,$id") >> n.Empdetail1() n.Empdetail2() n.Empdetail3() >

Kotlin Anonymous class 2

In the second example, we used to interface and implement the interface with a separate class, and we can create the object by using the object keyword.

Example #3

package one; open class Days < open fun Sunday() < println("Welcome To My Domain Its the Sunday") >fun Monday() < println("Welcome To My Domain Its the Monday") >fun Tuesday() < println("Welcome To My Domain Its the Tuesday") >> fun main(args:Array) < var n=object:Days()< fun Wednesday() fun Thrusday() fun Friday() fun Saturday() > n.Wednesday() n.Thrusday() n.Friday() n.Saturday() >

we created the open class and method

In the final example, we created the open class and method used to create the anonymous class object in the kotlin.

Conclusion

In the concluded part, the anonymous class is one of the inner classes type used to implement the functions and other logic, but the class name is not mentioned on the code. By using the object keyword to create the object, we can implement and override the methods from both class and interfaces.

This is a guide to Kotlin anonymous class. Here we discuss the introduction, syntax, and working of anonymous class in kotlin along with different examples and code implementation. You may also have a look at the following articles to learn more –

25+ Hours of HD Videos
5 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

92+ Hours of HD Videos
22 Courses
2 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

83+ Hours of HD Videos
16 Courses
1 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

KOTLIN Course Bundle — 4 Courses in 1
12+ Hour of HD Videos
4 Courses
Verifiable Certificate of Completion
Lifetime Access
4.5

Источник

Читайте также:  Jquery подключить файл php
Оцените статью