Emre
Emre

Reputation: 31

Kotlin fragment if statement issue

In my code (in same class) i just call the function like this:

menuChange(ClickerFragment())

And my function is here:

fun menuChange(frag: Fragment){
    if(frag == ClickerFragment()){
        println("Statement worked!")
    }
    println("Function worked!")
}

When i run this in console screen, i can see only "Function worked!" text. Idk why if statement not working. But however "frag" is always equal in this case.

Upvotes: 0

Views: 289

Answers (4)

Guhanmuthu Selvaraj
Guhanmuthu Selvaraj

Reputation: 253

Reason for println("Statement worked!") not working. we are creating the new Instance of the ClickerFragment() and checking equals (frag) with some other object. which never be true. (we checking both instances are the same). We have check frag is a type of ClickerFragment(). This can be achieved by using is

if(frag is ClickerFragment){
        println("Statement worked!")
    }

Upvotes: 0

Samir Bhatt
Samir Bhatt

Reputation: 3261

You need to check instance of fragment instead of equals. It should like this :

fun menuChange(frag: Fragment){
    if(frag is ClickerFragment){
        println("Statement worked!")
    }
    println("Function worked!")
}

Upvotes: 2

ChristianB
ChristianB

Reputation: 2690

They can never be equal, because you are creating a new ClickerFragment() instance in your if condition.

You should use the is operator for checking if an instance is a certain class type:

fun menuChange(frag: Fragment){
    if(frag is ClickerFragment){
        println("Statement worked!")
    }
    println("Function worked!")
}

Documentation

Upvotes: 3

sdex
sdex

Reputation: 3763

You need to change your check to
if(frag is ClickerFragment){

Upvotes: 2

Related Questions