How to make classes in Kotlin?

A Kotlin class is defined in its simplest form by declaring its members in the class declaration itself.






class Book(var bookname:String,var subject:String,var price:Int) {

    override fun toString(): String
    {
       return "Book Name=$bookname, Subject = $subject, Price=$price"
    }


}
fun main(args: Array<String>)
{
    var b=Book("Basic C","C",100)
    println(b.toString())
}

Varanasi Software Junction: Kotlin Class




The portion in bold is the toString method and gives a string representation of the class.

Class with init block

class Book(var bookname:String,var subject:String,var price:Int) {

    init {
        println("book name stored $bookname")
    }



    init {
        println("book subject stored $subject")
    }
    init {
        println("book price stored $price")
    }
    val discountedprice:Double =price.toDouble()*90.0/100.0





    override fun toString(): String
    {
       return "Book Name=$bookname, Subject = $subject, Price=$price, Discounted Price=$discountedprice"
    }
}
fun main(args: Array<String>)
{
    var b=Book("Basic C","C",100)
    println(b.toString())
}


Varanasi Software Junction: Kotlin Class


Class with static method


class Book(var bookname:String,var subject:String,var price:Int) {

    init {
        println("book name stored $bookname")
    }



    init {
        println("book subject stored $subject")
    }
    init {
        println("book price stored $price")
    }
    val discountedprice:Double =price.toDouble()*90.0/100.0

    companion object {
        val classdetails = "This is a book class"
        fun details():String { return classdetails }
    }



    override fun toString(): String
    {
       return "Book Name=$bookname, Subject = $subject, Price=$price, Discounted Price=$discountedprice, Detail = $classdetails"
    }


}
fun main(args: Array<String>)
{
    var b=Book("Basic C","C",100)
    println(b.toString())
    println(Book.details())
}



Varanasi Software Junction: Kotlin Class





Post a Comment

0 Comments

Me