Deniz Göçer
Deniz Göçer

Reputation: 55

I get a "Val cannot be reasigned error" even though I assigned the variable as var?

I'm trying to add "copy to clipboard" functionality to an application. I added a setOnClickListener on the image button for copying and wrote the code below. I still get "val cannot be reassigned" error on "clipBoard.primaryClip = clip" line

            var clipBoard: ClipboardManager = getActivity()?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val StrEdtFirtname = etNoteDesc.text.toString()
            val clip = ClipData.newPlainText("Copied text",StrEdtFirtname)
            clipBoard.primaryClip = clip
            Toast.makeText(requireContext(), "Copied text", Toast.LENGTH_SHORT).show()
        }

Upvotes: 0

Views: 81

Answers (1)

Dharmender Manral
Dharmender Manral

Reputation: 1520

Try with the following code.

var clipBoard: ClipboardManager = getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
     val StrEdtFirtname = etNoteDesc.text.toString()
    val clip = ClipData.newPlainText("Copied text",StrEdtFirtname)
    clipBoard.apply {
        setPrimaryClip(clip)
    }

Upvotes: 1

Related Questions