Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does `class C(val field: T): T by field` mean?

Tags:

kotlin

I recently came across the following class declaration:

class C(val field: T): T by field

where T is an interface.

What is this technique called?

What is the effect of this declaration?

like image 870
Some Noob Student Avatar asked Apr 12 '20 06:04

Some Noob Student


People also ask

What is a field in a class C++?

The Field class represents a field in a database record (object or instance of a database class).

What is meant by field in C#?

A field is a variable of any type that is declared directly in a class or struct. Fields are members of their containing type. A class or struct may have instance fields, static fields, or both. Instance fields are specific to an instance of a type.

What is the meaning of class field?

Given a set of primes, a field is called a class field if it is a maximal normal extension of the rationals which splits all of the primes in , and if is the maximal set of primes split by K. Here the set. is defined up to the equivalence relation of allowing a finite number of exceptions.

What does field in Java mean?

A Java field is a variable inside a class. For instance, in a class representing an employee, the Employee class might contain the following fields: name. position.


1 Answers

This is called delegation, specifically it is a type of delegation known as implementation by delegation.

By doing this, the class C implements the interface using the other object.

i.e. when you call the method (function) defined in the interface then the call is going to get transferred to the object you delegated in your case it is the field

interface T {
    fun print()
}
class TImpl: T {
    override fun print() = print("Hello World!")
}

class C(val field: T) : T by field {...}

fun main() {
    val c = C(TImpl())
    c.print()                 //Prints: Hello World!
}

Here the print() call gets transferred to TImpl because class C implements T by using field.

like image 165
Animesh Sahu Avatar answered Nov 27 '22 00:11

Animesh Sahu