Wednesday, May 20, 2020

Data Class , Object Declaration and Companion Object

Data class :-

Contain method such hashcode(), equal(), to String() ,copy()- BuiltIn
In data class, primary constructor contain variable(properties)

fun main(Args : Array<String>)
{
var user1 = user("sum",10)
var user2 = user("sum",10)
println(user1.toString())    //using inbuilt function of the data class (print everything!!) 

if(user1 == user2)
println("equals")
else
println("not equals")

var newuser  = user1.copy(id=25)  //copy the id to new instance
prinln(newuser)
}

data class user(var name:String,var id:String)  //this is data class

Object Declaration :-

Acted as class having static method and Variables
use keyword 'Object'
Cannot have constructor
can have superclass & init

fun main(args:Array<String>){
    customerdata.count = 98
    println(customerdata.count)
    customerdata.count =22
    println(customerdata.count)
    println(customerdata.type())
  customerdata.mymethod("Hello")}

open class supera{
    open fun mymethod() {
        println("mysuperclass") }}

object customerdata : supera(){   //object declaration
var count:Int = -1   //behaves like static method
 fun type():String {
        return "Indian"}

  fun mymethod(input:String) {   //behaving like static method
 super.mymethod()
        println(input)}}


Companion Object :- 

Same as object , but declared within class


fun main(args : Array<String>){
    my_class.count =78
    println(my_class.count)
    println(my_class.customer_type())}

class my_class{
    companion object{
        var count : Int = -1
 fun customer_type():String {
           return "Indian" } }}



















No comments:

Post a Comment

Null Safety , Lazy Keyword and LateInit Keyword

Null Safety :- Safe call  ( ? )    use it if you don't mind getting null values Not Null Insertion ( !! )  use if you are sure that val...