【问题标题】:Assign a new value to variables by using method in Kotlin?使用 Kotlin 中的方法为变量分配新值?
【发布时间】:2017-11-26 16:17:10
【问题描述】:

在 Java 中,我可以使用 [class-name].[method] 来更改类中变量的值,例如:

 public class Main {    
    public static void main(String[] args) {
        // Prints "Hello, World" to the terminal window.
        test.teste();
        test.printlnvar();
    }        
}

class test{
    public static int a = 0;
    public static int b = 0;
    public static void teste(){
        a = 9;
        b = 12;
    }
    public static void printlnvar(){
        System.out.println("the value of A: " + a);
        System.out.println("the value of B: " + b);
    }
}

但是,我如何在 Kotlin 中做到这一点?我尝试了,但在下面的代码中,变量 IntColumn 和 IntRow 的结果始终为 0:

public class drawTriangle{       
   public var IntColumn:Int = 0;
   public var IntRow:Int = 0;

  fun drawTriangle(){
    this.inputRowandColumn();
    this.Printvalue();
  }

  fun inputRowandColumn(){
    IntColumn = 12;
    IntRow = 3;
  }

  fun Printvalue(){
    println("the value of rows is: ${IntRow}");
    println("the value of column is: ${IntColumn}");
  }
}

fun main(args: Array<String>){
    drawTriangle().inputRowandColumn();
    drawTriangle().Printvalue();
}

【问题讨论】:

    标签: java kotlin


    【解决方案1】:

    在您的 main 函数中,您创建了 drawTriangle 类的 2 个单独实例,因此有两组变量 - 其中一组您更改,一组您打印。一个简短的修复:

    fun main(args: Array<String>){
        val d = drawTriangle()
        d.inputRowandColumn()
        d.Printvalue()
    }
    

    附:您的 Kotlin 代码与您的 Java 代码截然不同。在您的 Java sn-p 中,您使用 2 个属于一个类的 static 字段。但是在 Kotlin sn-p 中,您使用 2 个成员属性,需要在其中存储实例。

    附言你的 Kotlin 代码有点像 C#。在学习一门新语言时,使用该语言的命名约定并不是一个坏主意;)

    【讨论】:

    • 感谢您的回答。但是,有没有其他办法?
    【解决方案2】:

    我不确定你为什么要这么做。根据 voddan,您的代码不等效。 Java 使用与类相关联的静态变量,而不是实例,因此您可以直接从静态“main”方法访问它们。

    Kotlin 将类(静态)项与实例项分开。如果定义类,则只能实例化实例并使用它们。

    如果您真的想在 Kotlin 中实现您的尝试,您需要使用“对象”而不是“类”。 Kotlin 中的对象是单例。以下是您在 Kotlin 中的编写方式。

    object drawTriangle {
        var intColumn: Int = 0
        var intRow: Int = 0
    
        fun drawTriangle() {
            this.inputRowandColumn()
            this.printvalue()
        }
    
        fun inputRowandColumn() {
            intColumn = 12
            intRow = 3
        }
    
        fun printvalue() {
            println("the value of Rows is: $intRow")
            println("the value of Column is: $intColumn")
        }
    }
    
    fun main(args: Array<String>) {
        drawTriangle.inputRowandColumn()
        drawTriangle.printvalue()
    }
    

    请注意,我删除了“公开”,因为 Kotlin 的默认设置是公开的。删除了分号,并重新命名以符合 Kotlin 命名标准。

    【讨论】:

      猜你喜欢
      • 2022-06-11
      • 1970-01-01
      • 2011-04-15
      • 2021-03-04
      • 1970-01-01
      • 1970-01-01
      • 2010-10-15
      • 1970-01-01
      • 2011-11-14
      相关资源
      最近更新 更多