Issue
I am a novice at android studio and I am trying to make a simple calculator that takes a string and returns a value.
The issue is that when writing the code to initialize a "Button" object, it believes I am trying to call a function. It shows an error that says that:
Function invocation 'Button(...) expected
But I am not trying to call a function for button just make a Button object.
This is my main activity file:
package com.example.myfirstcalc
import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)
Button calcBtn = (Button) findViewById(R.id.calculateBtn);
}
}
This is the activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/expressionEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="124dp"
android:ems="10"
android:hint="Enter an expression"
android:inputType="textPersonName"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="@+id/calculateBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/expressionEditText"
app:layout_constraintVertical_bias="0.089" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/calculateBtn"
app:layout_constraintVertical_bias="0.124" />
</androidx.constraintlayout.widget.ConstraintLayout>
Solution
The problem is due to incorrect syntax. You are mixing the syntax of Java
and Kotlin
To write it correctly in Kotlin
, change the line:
Button calcBtn = (Button) findViewById(R.id.calculateBtn);
to:
val calcBtn = findViewById(R.id.calculateBtn) as Button
To know basic information about Android applications in Kotlin
see here. To learn the basic syntax of Kotlin
, visit here.
Answered By - cse
Answer Checked By - David Goodson (JavaFixing Volunteer)