Kotlin idiom for doing stuff in a ctor


#1

Hi.  I am getting my feet wet with Kotln, and I'm enjoying it.

Context:  IJ EAP build 114.145, plugin version kotlin-plugin-0.1.1358.zip.

I could not quite discern by reading the wiki how to do non-trivial stuff in a class constructor.  e.g., what is the Kotlin equivalent of this Java class?

public class Account1 {

  public final String userName;

  public Account1() {
  // load properties from a classpath resource and assign a value to “userName”
  }
}


I tried this, but it doesn’t work (inputstream is null):
class Account1() {   var userName : String? = ""   var password : String? = ""   var apiKey : String? = ""

  {
  val p = java.util.Properties()
  val inputStream = ClassLoader.getSystemResourceAsStream("/mailchimp.properties")
  p.load(inputStream)
  
  userName = p.getProperty(“username”)
  password = p.getProperty(“password”)
  apiKey = p.getProperty(“apikey”)
  }
}

Also, how do you getClass(), so you can get a classpath resource, on in a Kotlin object instance?  That static ClassLoader.getSystemResourceAsString() is not quite what I had in mind to get the classpath resource.

Thanks much.
Mark


#2

I tried this, but it doesn't work (inputstream is null):
If the input stream is null, it means that the constructor gets invoked, but you have a problem with your input stream. So, I think the constructor question doesn't need an answer. Correct me if I'm wrong.

I personally suspect this line:

  val inputStream = ClassLoader.getSystemResourceAsStream("/mailchimp.properties")
For it goes to system resourses which might not be the right place...

Also, how do you getClass(), so you can get a classpath resource, on in a Kotlin object instance?  That static ClassLoader.getSystemResourceAsString() is not quite what I had in mind to get the classpath resource.
You can say

``

foo.javaClass

to do that.

Feel free to ask more questions if you have them. Good luck!


#3

Thank you, kindly.  That helped.

This works

class Account1() {   var userName : String? = ""   var password : String? = ""   var apiKey : String? = ""   {   val p = Properties()   val clazz = javaClass   val inputStream = clazz.getResourceAsStream("/mailchimp.properties")   p.load(inputStream)   userName = p.getProperty("username")   password = p.getProperty("password")   apiKey = p.getProperty("apikey")   } }