1

I'm learning Kotlin. I have the following code:

class Person(name: String, surname: String) {

}

fun main(args: Array<String>) {
    val p = Person("Tonj", "Manero")
    println("Hello, world! ${p.name}")
}

This code does not work, it give an error during compilation. The question is: how can i use a property value in a string template in Kotlin? Tnx

2
  • also see data classes Commented Mar 8, 2018 at 21:20
  • 2
    There is actually no need for a data class in this case, just properties. Commented Mar 9, 2018 at 7:08

1 Answer 1

9

Because you are declaring constructor arguments, not properties. You have to declare them as val or var.

class Person(val name: String, val surname: String) {

}

If you leave off the val or var, Kotlin treats them as arguments to the constructor itself. They would be available for use in any field initializers or init blocks, but they won't be declared as properties.

Sign up to request clarification or add additional context in comments.

Comments

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.