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?
The Field class represents a field in a database record (object or instance of a database class).
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With