Reputation: 81
I've tried hundreds of ways to resolve this reference problem:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
val dm = DataManager()
val adapterCourses = ArrayAdapter<CourseInfo>(context: this,
android.R.layout)
but in ArrayAdapter<CourseInfo>(context: this, android.R.layout)
I get unresolved reference: context and I have no idea why.
Android Studio version: 3.3.2 Kotlin version: 1.3.21
Could anyone help me?
Upvotes: 7
Views: 12703
Reputation: 71
I had a similar error message because I didn't import the Context
.
If you haven't explicitly imported Context
, try adding this to your import list near the start of your Activity
file:
import android.content.Context
Upvotes: 7
Reputation: 2852
The column in Kotlin is used for some things, but not when passing named arguments. The syntax for passing a named parameter is parameterName = parameterValue
.
When you write context = this
, while passing a parameter, you are simply referring to the parameter context
of the function you are calling, explicitly saying that this
has to correspond to that context
parameter. This is not very useful in this case unless you want to be very explicit.
The usefulness of using named arguments arise when you are dealing with optional parameters or when you are passing the parameters out of order.
E.g.
// DECLARATION of function abc
fun abc(s: String = "", i: Int = 0)
// USAGE of function abc passing only an Int
abc(i = 314)
The function abc
has two parameters and they have a default value. In this case, you can avoid passing any parameter if you are fine with the defaults.
But if you only want to pass i
, you can do it by specifying its name, as done in the example.
Similarly, you can choose to pass parameters out of order, in that case, you'll do:
abc(i = 314, s = "something")
Upvotes: 0