2

I have read the following syntax. I have no idea why scope resolution operator is used in it.

class XyzFragment : Fragment() {

    lateinit var adapter: ChatAdapter

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        if (!::adapter.isInitialized) { <-- This one
            adapter = ChatAdapter(this, arrayListOf())
        }
    }
}

I want to know what is :: in if (!::adapter.isInitialized) { statement.

1

1 Answer 1

6

:: is a short form for this:: in Kotlin.

:: is a operator to creates a member reference or a class reference. For example,

class Test {        
    fun foo() {

    }

    fun foo2(value: Int) {

    }

    fun bar() {
        val fooFunction = ::foo
        fooFunction.invoke()  // equals to this.foo()
        val foo2Function = ::foo2
        foo2Function.invoke(1)  // equals to this.foo2(1)
        val fooFunction2 = Test::foo
        val testObject = Test()
        fooFunction2.invoke(this) // equals to this.foo()
        fooFunction2.invoke(testObject) // equals to testObject.foo()
    }
}

This is mainly used in reflection and passing function.

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

2 Comments

Is it still called a "scope resolution" operator? Couldn't see that name anywhere in the documentation.
@VishnuHaridas No, because it never call like that. Here may be what you needed. Also, you should ask a new question instead of writing comment.

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.