【问题标题】:How to return an object from a function in Kotlin?如何从 Kotlin 中的函数返回对象?
【发布时间】:2021-07-20 19:44:43
【问题描述】:

我的代码:

class Point(xA: Int)
{
    val x = xA
}

fun AddVectorToPoint(i: Int): Point()
{
    val x: Int = 1 + i
    val obj = Point(x)
    return obj
}

fun main()
{
    val points = mutableListOf(Point(0))
    points.add(AddVectorToPoint(2))
}

但是当我尝试编译它时,我得到“test.kt:6:36: error: expecting a top level declaration > fun AddVectorToPoint(i: Int): Point() {” 我做错了什么?

【问题讨论】:

  • fun AddVectorToPoint(i: Int): Point() 行中删除返回类型括号。它必须喜欢this
  • 另外,函数名通常以小写字母开头;见Kotlin coding convensions

标签: object kotlin return


【解决方案1】:

去掉返回类型后面的括号

fun AddVectorToPoint(i: Int): Point
{
    val x: Int = 1 + i
    val obj = Point(x)
    return obj
}

或者为了更简洁:

fun AddVectorToPoint(i: Int) = Point(1 + i)

【讨论】:

    猜你喜欢
    • 2020-06-17
    • 1970-01-01
    • 2015-12-15
    • 1970-01-01
    • 2012-02-29
    • 2016-03-17
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多