2

Explanation : I am trying to cast my view elements in kotlin. In kotlin there is only possible in onCreate() but the problem is the scope of this variable or view elements inside the onCreate() method only. I tried to declare outside the onCreate() and inside the class. It raised me an error.

Please help me to resolve.

class MainActivity : AppCompatActivity()
{ 
    var x:Int = 10; 
    var lblValue:TextView=findViewById(R.id.lbl_value); 

    override fun onCreate(savedInstanceState: Bundle?) { 
       super.onCreate(savedInstanceState) 
       setContentView(R.layout.activity_main) 
       lblValue.setText(""+getSum(10,20)); 
    } 

    fun getSum(a:Int,b:Int): Int{ 
      return a+b; 
    } 
} 
Hardik Trivedi
  • 5,677
  • 5
  • 31
  • 51
Milan Gajera
  • 962
  • 2
  • 14
  • 41
  • could you post your onCreate code? – Sachin Chandil Nov 06 '17 at 07:32
  • class MainActivity : AppCompatActivity(){ var x:Int = 10; var lblValue:TextView=findViewById(R.id.lbl_value); override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) lblValue.setText(""+getSum(10,20)); } fun getSum(a:Int,b:Int): Int{ return a+b; } } – Milan Gajera Nov 06 '17 at 08:34
  • Multiple mistakes. You are finding view outside onCreate. You can never get view object until it's set. Find the view always after onCreate. You don't need to put semicolons, its Kotlin :) In Kotlin also there is no need to find the view by id. Read this https://kotlinlang.org/docs/tutorials/android-plugin.html – Hardik Trivedi Nov 06 '17 at 09:32

0 Answers0