Kotlin - Factory class 有属性问题

Kotlin - Factory class with properties issues

我正在尝试用 Kotlin 编写工厂 class。在 Java 中:

public class MyFactory {
   private static MyFactory instance = null;
   private Properties props = null;
   private FirstClass firstInstance = null;
   private SecondClass secondInstance = null;

   private MyFactory() {
     props = new Properties();
     try {
       props.load(new FileInputStream("path/to/config"));

       String firstClass = props.getProperty(“first.class”);
       String secondClass = props.getProperty(“second.class”);
       firstInstance = (FirstClass) Class.forName(firstClass).newInstance();
       secondInstance = (SecondClass) Class.forName(secondClass).newInstance();
     } catch (Exception ex) {
        ex.printStackTrace();
     }
  }
  static {
    instance = new MyFactory();
  }
  public static MyFactory getInstance() {
    return instance;
  }

  public FirstClass getFirstClass() {
    return firstInstance;
  }

  public SecondClass getSecondClass() {
    return secondInstance;
  }

}

我在尝试用 Kotlin 重写它时遇到了一些问题。 我尝试先在 try.kotlinlang.org 上使用 Java 转换器生成代码。结果是:

class MyFactory private constructor() {
  private var props: Properties? = null

  private var firstInstance: FirstClass? = null
  private var secondInstance: SecondClass? = null

  init {
      try {
          props!!.load(FileInputStream("path/to/conf"))

          val firstClass = props!!.getProperty("prop")
          val secondClass = props!!.getProperty("prop")

          firstInstance = Class.forName(firstClass).newInstance() as FirstClass
          secondInstance = Class.forName(secondClass).newInstance() as SecondClass
      } catch (ex: Exception) {
          ex.printStackTrace()
      }
  }

  companion object {
      var instance: MyFactory? = null

      init{
          instance = MyFactory()
     }
   }
}

我正在使用 IntelliJ IDEA 15,它说这个 class 没有 getInstance() 方法,但是当我尝试实现它时它说:

  Platform declaration clash: The following declarations have the same JVM signature:
fun <get-instance>(): my.package.MyFactory?
fun getInstance(): my.package.MyFactory?

我记得,getter 仅在数据 classes 中自动实现。 有人可以澄清这种情况,或者可以告诉我如何实施这个的正确方法吗? 更新:
我通过引用属性本身在 Kotlin 中使用这个 class,例如。 MyFactory.instance!!.firstInstance,但这样做感觉不对。

解释如下:

Kotlin 编译器为所有属性创建 getters 和 setter,但它们仅在 Java 中可见。在 Kotlin 中,属性是惯用的,当你使用 Java 类 时它们甚至是 generated from Java getter and setter pair

因此声明方法 getInstance 确实与 auto-generated getter that will be visible in Java code 冲突。

如果您需要自定义 getter 行为,请使用 getter 语法:

var instance: MyFactory? = null
get() {
    /* do something */
    return field
}

在此示例中,field 是软关键字,表示 属性 的支持字段。

已记录 here

顺便说一下,object declaration 似乎很适合你的情况。