1

Whilst converting a rather simple application from Java to Kotlin I came across one 'problem' I can't seem to fix.

I have a class ScanInfo that looks like this in Java (without getters and setters)

public class ScanInfo {
    private String source;
    private String label_type;
    private String data;

    public ScanInfo(Intent intent) {
        ... Get Info from intent and assign the values ...
        this.source = ...
        this.label_type = ....
        this.data = ....
    }
}

Now in Kotlin i can create the class

class ScanInfo (var source: String, var label_type: String, var data: String)

But I have no idea how to get it to work so I can create a ScanInfo object with Intent as parameter. I tried with companion, object, companion object but I can't seem to find the right syntax.

Am I wrong to look for such a solution while using Kotlin or am I just not using the right kotlin-constructor? If it's possible, how can I create a ScanInfo object with an Intent as parameter?

var result = ScanInfo(intent)

Thanks in advance.

1 Answer 1

2

That's the way:

class ScanInfo(intent: Intent) {
    private val source = intent.source
    private val labelType = intent.labelType
    private val data = intent.data
}

OR

class ScanInfo(intent: Intent) {
    private val source: String
    private val labelType: String
    private val data: String

    init {
        source = intent.data
        labelType = intent.data
        data = intent.data
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

you need to add getters/setters too or change the visibility
Not sure if OP needs getters/setters for his class, but yes, you're right.
using the init method is the best choice
I've use the second option because I had more actions to be completed before getting the source/label_type/data information. By removing the private indication of the declaration and changing them to var's, I have my needed solution. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.