Setaros Pplkn
Setaros Pplkn

Reputation: 21

why when I call java class from kotlin project program alway stop working

This is my MainActivity

class MainActivity : AppCompatActivity() {

      override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         setContentView(R.layout.activity_main)
         lateinit var maT : mat
         var num : Int = maT.two()
      }
}

And this is my java class

public class mat {

      public int two(){
        return 2;
      }
}

They are in the same package

Upvotes: 0

Views: 48

Answers (1)

Dean
Dean

Reputation: 2005

The problem is occurring because the maT property has not be initialised when you are calling

maT.two()

The documentation for lateinit states:

Accessing a lateinit property before it has been initialized throws a special exception that clearly identifies the property being accessed and the fact that it hasn't been initialized.

In order to fix the problem try:

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
     super.onCreate(savedInstanceState)
     setContentView(R.layout.activity_main)
     var maT = mat()
     var num : Int = maT.two()
  }
}

The change that was made was to remove lateinit and to instantiate an object of type mat :

var maT = mat()

FYI: You should consider using a capital at the start of a class e.g. Mat

Upvotes: 1

Related Questions