logo
down
shadow

How to initialise 'MutableMap' from constructor of data class in kotlin?


How to initialise 'MutableMap' from constructor of data class in kotlin?

By : arensonjr
Date : January 12 2021, 01:40 AM
should help you out You can do one of the following:
Extracting the init logic into a companion function:
code :
data class MyDataClass(
    val myArr: ArrayList<Char>,
    val myMap: MutableMap<Char, MutableMap<String, String>>
) {
    constructor(n: Int) : this(
        ArrayList(foo(n)),
        foo(n).map { it to mutableMapOf<String, String>() }.toMap().toMutableMap()
    )

    companion object {
        fun foo(n: Int) = (0 until n).map { ('A' + it) }
    }
}
data class MyDataClass(
    val myArr: ArrayList<Char>,
    val myMap: MutableMap<Char, MutableMap<String, String>>
) {
    constructor(n: Int) : this(ArrayList((0 until n).map { ('A' + it) }))

    constructor(list: ArrayList<Char>) : this(
        list,
        list.map { it to mutableMapOf<String, String>() }.toMap().toMutableMap()
    )
}



Share : facebook icon twitter icon
Initialise protected data members from derived class constructor

Initialise protected data members from derived class constructor


By : KDR DZ
Date : March 29 2020, 07:55 AM
may help you .
Is it that I can't initialise protected members using Initalizer list or something?
code :
class Base {

    explicit Base(int i) : m(i)
    {}
protected:
    int m;
};

class Derived : public Base {
    explicit Derived(int i) : Base(i)
    { }
};
Initialise a class with a parameterized constructor in the constructor of a Service Class using Castle Windsor

Initialise a class with a parameterized constructor in the constructor of a Service Class using Castle Windsor


By : Mahmoud Mekkawy
Date : March 29 2020, 07:55 AM
it helps some times One primary method* of providing run-time, user-driven, or otherwise dynamic dependencies is using factories to create your objects. Castle Windsor provides several different facilities to help with this, or you can use the kernel and implement a factory yourself.
Windsor's facility allows you to provide delegate-based factories, which are just methods for creating an object. You could use that here, but you lose some flexibility in what you can create (if you were to replace the implementation of ICalculator to some other class, you'd have to update this method).
code :
public class Calculator : ICalculator
{
    string Operator;

    public Calculator(string operator)
    {
        Operator=operator;
    }
}
public interface ICalculatorFactory
{
    ICalculator Create(string operator);
}
kernel.Register(Component.For<ICalulatorFactory>().AsFactory());
public class CalculatorUseExample
{
    private readonly ICalculator addCalculator;
    private readonly ICalculator subCalculator;

    public CalculatorUseExample(ICalculatorFactory calculatorFactory)
    {
        addCalculator = calculatorFactory.Create("+");
        subCalculator = calculatorFactory.Create("-");
    }
}
public interface ICalculatorServiceFactory
{
    ICalculatorService Create(string operator);
}

public class CalculatorService : ICalculatorService
{
    private readonly ICalculator Calculator;

    public CalculatorService(string operator, ICalculatorFactory calculatorFactory)
    {
        Calculator=calculatorFactory.Create(operator);   
    }
}
public interface ICalculatorServiceFactory
{
    ICalculatorService Create(ICalculator calculator);
}

public class CalculatorService : ICalculatorService
{
    private readonly ICalculator Calculator;

    public CalculatorService(ICalculator calculator)
    {
        Calculator=calculator;
    }
}

public class CalculatorServiceUseExample
{
    public CalculatorServiceUseExample(ICalculatorServiceFactory calculatorServiceFactory, ICalculatorFactory calculatorFactory)
    {
        var addCalculator = calculatorFactory.Create("+");
        var service = calculatorServiceFactory.Create(addCalculator);

        // TODO: use the service
    }
}
public class CalculatorService : ICalculatorService
{
    private readonly ICalculatorFactory calculatorFactory;
    private ICalculator calculator;

    public CalculatorService(ICalculatorFactory calculatorFactory)
    {
        // store the factory until we need it
        this.calculatorFactory = calculatorFactory;
    }

    public void ChangeCalculatorServiceClient(string operator)
    {
        // A new operator, we'll need a new calculator
        calculator = calculatorFactory.Create(operator);
    }
}
using Castle.Facilities.TypedFactory;

public class WindsorInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<IGreeting, Greeting>(),
            Component.For<IGreetingFactory>().AsFactory(),
            Component.For<IGreetingService, GreetingService>(),
            Component.For<ILanguageFactory, LanguageFactory>());
    }
}

public interface ILanguageFactory
{
    ILanguage Create(string language);
}

public class LanguageFactory : ILanguageFactory
{
    private readonly IKernel kernel;

    public LanguageFactory(IKernel kernel)
    {
        this.kernel = kernel;
    }

    public ILanguage Create(string language)
    {
        switch (language)
        {
            case "S":
                return kernel.Resolve<Spanish>();
            default:
                throw new ArgumentException();
        }
    }
}

public class GreetingService : IGreetingService
{
    private readonly IGreetingFactory greetingFactory;
    private readonly ILanguageFactory languageFactory;
    private IGreeting greeting;

    public GreetingService(IGreetingFactory greetingFactory, ILanguageFactory languageFactory)
    {
        // store the factory until we need it
        this.greetingFactory = greetingFactory;
    }

    public string SayHello (string strLanguage)
    {
        var language = languageFactory.Create(strLanguage);
        greeting = greetingFactory.Create(language);
        return greeting.SayHello();
    }
}
Data class constructor with two different constructor in Kotlin

Data class constructor with two different constructor in Kotlin


By : German Ros
Date : March 29 2020, 07:55 AM
I hope this helps . From the doc:
code :
class Person(val name: String) {
    constructor(name: String, parent: Person) : this(name) {
        parent.children.add(this)
    }
}
constructor( instituteName: String, city: String) : this("centerId"){
    this.instituteName=instituteName;
    this.city=city;

}
class InstituteSearchDetails {

    lateinit var centerId: String;
    lateinit var instituteName: String;
    lateinit var city: String;

    constructor(centerId: String) {
        this.centerId = centerId
    }

    constructor( instituteName: String, city: String)
    {
        this.instituteName=instituteName;
        this.city=city;
    }
}
sealed class InstituteSearchDetails {

    data class InstituteWithCenterId(val centerId: String): InstituteSearchDetails()
    data class InstituteWithNameAndCity(val name: String, val city: String): InstituteSearchDetails()

}

fun handleInstitute(instituteSearchDetails: InstituteSearchDetails) {

    when (instituteSearchDetails) {
        is InstituteSearchDetails.InstituteWithCenterId -> println(instituteSearchDetails.centerId)
        is InstituteSearchDetails.InstituteWithNameAndCity -> println(instituteSearchDetails.name)
    }

}
Initialise data class object to 1 or 2 arguements in kotlin?

Initialise data class object to 1 or 2 arguements in kotlin?


By : user3125047
Date : March 29 2020, 07:55 AM
like below fixes the issue to the answer over here Kotlin data class optional variable
Initialised default value to the data class
code :
data class ApiPost(
        @SerializedName("LoginId")  var userName: String ="",
        @SerializedName("Password") var password: String ="",
        @SerializedName("NewPassword") var newPassword: String ="",
        @SerializedName("FileType") var FileType: String ="",
        @SerializedName("UserId") var UserId: String ="",
        @SerializedName("CountryId") var CountryId: String ="",
        @SerializedName("DateOfBirth") var DateOfBirth: String ="",
        @SerializedName("Mobile") var Mobile: String ="",
        @SerializedName("CountryName") var CountryName: String ="",
        @SerializedName("CompanyName") var CompanyName: String ="",
        @SerializedName("IsAnonymous") var IsAnonymous: String ="",
        @SerializedName("EmployeeIssue") var EmployeeIssue: String ="",
        @SerializedName("DetailedInformation") var DetailedInformation: String ="",
        @SerializedName("EmployeeId") var EmployeeId: String ="",
        @SerializedName("EmployeeEmailId") var EmployeeEmailId: String ="",
        @SerializedName("FCMId") var FCMId: String =""
    )
ApiPost(userName = "ak@gmail.com", password = "12345")
(Kotlin) Pass argument from data class constructor to super constructor?

(Kotlin) Pass argument from data class constructor to super constructor?


By : Kamrul Hasan
Date : March 29 2020, 07:55 AM
will be helpful for those in need Data classes work differently than regular classes. As you have already noticed, data classes require properties in the constructors. Data classes and inheritance is hard, because you can't pass the values like in regular classes. And inheriting from a data class isn't possible either; they don't support open or abstract, which means it's final, and can't be inherited from.
Effectively, this isn't possible if you have a data class as the child:
code :
class Something(something: Int, else: Int) : Parent (something, else)
abstract class SuperClass {
    protected abstract val privateVal: Int
}
data class Overridden(override val privateVal: Int) : SuperClass()
Related Posts Related Posts :
  • How to implement this kotlin ReceiveChannel code properly
  • Implementing flow for Updation of state , do we have to use SendTransaction
  • What is the difference between "package" and "module" in Kotlin?
  • About type parameter of generic in Kotlin
  • How to set values to data class if some size is specified in kotlin?
  • Kotlin decomposing numbers into powers of 2
  • How to simply add another source to MediatorLiveData in kotlin?
  • How to avoid nest 「null check」by "?.let"?
  • Idiomatic way in kotlin to transform/append to a list?
  • Extension property inside class: Unresolved reference: errorResponse
  • How to extend enums in Kotlin?
  • Convert Long to String in Kotlin
  • Kotlin: Should mutableList be declared as Val or Var?
  • kotlin, where the return from inside the let go
  • Check if any array item is not empty
  • How can i call an interface in kotlin?
  • Kotlin test, how to run BeforeEach with DescribeSpec test style
  • Convince Kotlin compiler map has a key
  • how do you declare static property in kotlin?
  • Why I Cannot Access to this function?
  • Kotlin - How do I concatenate a String to an Int value?
  • Lambda as a function parameter -> accept methods only from particular class
  • Kotlin inline class in JUnit tests
  • How can Kotlin's Set be covariant when contains() takes E?
  • How to split on unicode whitespace in kotlin
  • This annotation is not applicable to target member property without backing field or delegate
  • How to check if a string is a valid email in android?
  • Please Explain to me this kotlin statement?
  • How to use kotlin's default parameter only if the input is not null?
  • Proposed change of `equals` to `==` can't be applied to Char and String?
  • Issue when trying to import Jacoco code coverage to SonarQube: Cannot import coverage information for file, coverage dat
  • brief function code for null check in kotlin
  • How to capture an argument that was passed to a mocked function and return it?
  • Kotlin, unresolved reference on everything in VSCode
  • Webflux saving to repository without using .block()
  • takeWhile which includes the actual value matching the predicate (takeWhileInclusive)
  • Kotlin - object type check against HashMap<String, String> shows warning
  • Primitive properties initialization in Kotlin
  • How can I improve readability of this Kotlin code?
  • How to parse JSON objects into an enum
  • Can I get a TableView column to use a Kotlin Exposed transaction when referencing a property?
  • How can I perform clean up actions upon closing a view in Kotlin/TornadoFX?
  • How to deal with nullable variables that are not null?
  • Defining a mutable property with a custom setter
  • Kotlin combined usage of arrow, lamda, ?, . , and let. what it mean?
  • Is it possible to extend a base class in a data class without overriding parameters?
  • Access a value from a Kotlin script using jsr-223
  • Single method to launch a coroutine
  • The value of NumberPicker doesn't change
  • MutableSet don't prevent duplicated content when using sealed class
  • Why 'is' keyword only work with open classes in kotlin?
  • Extension function override of `equals(Any?): Boolean`
  • How to check a string starts with a specified string in kotlin?
  • Generate data class attribute value only during creation
  • Redirect to absolute URL in Ktor
  • how do I readirect t another path
  • How to limit allowed file size (multipart-file) in Ktor
  • nested let blocks in kotlin and valiadation
  • Generic method for finding instances of classes with 'is' operator
  • Enumerate the extension properties defined in a package
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org