Kotlin constructors

I dont just get how to make emp variable and make program to ask id + name or just name, with ordinal id.
For example i like to ask
println(“Type name of employee:”)
var what??

fun main(args: Array) {
val emp = employee(1, “Harri”)
}
class employee(emp_id : Int , emp_name: String) {
val id: Int
var name: String

init {
    id = emp_id
    name = emp_name

    println("Employee id is: $id")
    println("Employee name: $name")
}

}

I’ve formatted your code. You can use “```run-kotlin” to format your code in a runnable way. You can even edit it right on the forum.

Here’s your code but I fixed the code style to match the official. I also fixed the quotes for the “Harri” string, which wasn’t double quote but instead was something else (could be just that I copied it from the forum and it wasn’t formatted).

fun main(args: Array<String>) {
    val emp = Employee(1, "Harri")
}
class Employee(empId : Int , empName: String) {
    val id: Int
    var name: String

    init {
        id = empId
        name = empName

        println("Employee id is: $id")
        println("Employee name: $name")
    }
}

I’d recommend looking for a tutorial series like JetBrains Academy | Kotlin Basics. It’s often much faster to learn by that kind of resource, or even just googling–forums are often slow to answer basic syntax errors or beginner problems.

2 Likes

I have coded only 1,5 weeks. Done over 80% from 5 ects course during that time. Course misses many parts and clarifies coding quite hard way. I try those, need to enroll.

Thanks!

Great! It’s always good to start and ask questions :slight_smile:

I like to point people to other source is that those sources often provide good coaching and detail that can’t be covered well in a forum.
If you have any smaller specific questions that aren’t covered in those resources, Slack is a good place to ask as people on Slack will often be able to quickly answer small questions.

There are some good books available like Atomic Kotlin.
Here’s a link to the learning resources: Learning materials overview | Kotlin

1 Like