1

I want to assign my context in constructor but when I use "this" ide warn me. How can I write code like this Java code below, but in Kotlin:

here is java code

public class LoginApiService {
    Context context;

    public LoginApiService(Context context) {
        this.context = context;
    }
}

here is what I want to do

class YLAService {


var context:Context?=null

class YLAService constructor(context: Context) {
    this.context=context
}

}

3
  • Warn you with what warning? Commented Jun 2, 2017 at 15:24
  • it isn't clear what you are trying to do, you should show the Kotlin code so we can see the final intent. And any warning/error you are having. Commented Jun 2, 2017 at 15:28
  • @JaysonMinard you are right, I editted my question Commented Jun 2, 2017 at 17:06

1 Answer 1

7

In Kotlin, if you provide a var or val in the constructor, it automatically becomes available as a property you can use. No other assignment is required.

class LoginApiService(val context: Context) {

   // Example...
   fun doSomething() {
      context.doSomethingOnContext()
   }
}
Sign up to request clarification or add additional context in comments.

3 Comments

you could provide an example with constructor keyword
using the constructor keyword for no reason is not idiomatic, what @todd presented is typical code.
I edit my question and I need to write something inside my constructor.

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.