Explorer exe неизвестная ошибка

I want to assign my class variable in constructor, but I get an error ‘expecting member declaration’

class YLAService {

    var context:Context?=null

    class YLAService constructor(context: Context) {
        this.context=context;// do something
    }
}

Shubham Suryavanshi's user avatar

asked Jun 5, 2017 at 12:15

hugerde's user avatar

1

In Kotlin you can use constructors like so:

class YLAService constructor(val context: Context) {

}

Even shorter:

class YLAService(val context: Context) {

}

If you want to do some processing first:

class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}

If you really want to use a secondary constructor:

class YLAService {

  val context: Context

  constructor(context: Context) {
    this.context = context
  }

}

This looks more like the Java variant, but is more verbose.

See the Kotlin reference on constructors.

answered Jun 5, 2017 at 12:16

nhaarman's user avatar

nhaarmannhaarman

98.7k55 gold badges247 silver badges278 bronze badges

3

I’ll just add some info and give real example. When you want to initialize class && trigger some event, like some method, in Python we can simply call self.some_func() being in __init__ or even outside. In Kotlin we’re restricted from calling simple in the context of the class, i.e.:

class SomeClass {
    this.cannotCallFunctionFromHere()
}

For such purposes I use init. It’s different from constructor in a way that we don’t clutter class schema && allows to make some processing.

Example where we call this.traverseNodes before any further actions are done with the methods, i.e. it’s done during class initialization:


class BSTIterator(root: TreeNode?) {
    private var nodes = mutableListOf<Int>()
    private var idx: Int = 0
    
    init {
        this.traverseNodes(root)
    }
    
    
    fun next(): Int {
        val return_node = this.nodes[this.idx]
        this.idx += 1
        return return_node
    }

    fun hasNext(): Boolean {
        when {
            this.idx < this.nodes.size -> {
                return true
            } else -> {
                return false
            }
        }
    }
    
    fun traverseNodes(node: TreeNode?) {
        if(node!!.left != null) {
            this.traverseNodes(node.left)
        }
        this.nodes.add(node.`val`)
        if(node!!.right != null) {
            this.traverseNodes(node.right)
        }
    }

}

Hope it also helps someone

answered Jan 5, 2022 at 7:09

SleeplessChallenger's user avatar

#android-studio #kotlin

#android-studio #kotlin

Вопрос:

Я изучаю программирование на Android (начальный уровень) и следую руководству. Я получаю сообщение об ошибке при запуске / сборке проекта. Expecting member declaration . Я проверил код на наличие опечаток и синтаксических ошибок. Я погуглил это, но я просто не уверен, что это значит или что искать, чтобы это исправить.

Другие классы, используемые в проекте, автоматически просматриваются классом MainActivity?

Код частично:

 MainActivity.kt:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    val friendlyDestroyer = Destroyer("Invincible")
    val friendlyCarrier = Carrier("Indomitable")

    val enemyDestroyer = Destroyer("Grey Death")
    val enemyCarrier = Carrier("Big Grey Death")

    val friendlyShipyard = ShipYard()

    friendlyDestroyer.takeDamage(enemyDestroyer.shootShell())
    friendlyDestroyer.takeDamage(enemyCarrier.launchAerialAttack())

    // Fight back
    enemyCarrier.takeDamage(friendlyCarrier.launchAerialAttack())
    enemyCarrier.takeDamage(friendlyDestroyer.shootShell())
    ...
 

Любая строка, в которой есть экземпляр класса с вызовом функции, показывает red squiggly line и ошибку.

В строке: friendlyDestroyer.takeDamage(enemyDestroyer.shootShell()) отображается expecting member declaration ошибка практически в каждой части строки.

Это происходит при каждом экземпляре класса, вызывающего класс.

Я не вижу никаких ошибок для других классов / файлов.

 Destroyer.kt:

package com.johndcowan.basicclasses

class Destroyer(name: String) {
    // what is the name of the ship
    var name: String = ""
        private set

    // what type of ship is it
    // alwys a destroyer
    val type = "Destroyer"

    // how much the ship can take before sinking
    private var hullIntegrity = 200

    // how many shots left in the arsenal
    var ammo = 1
      // cannot be directly set externally
      private set

    // no external access whatsoever
    private var shotPower = 60

    // has the ship been sunk
    private var sunk = false

    // this code runs as the instance is being initialized
    init {
        // so we can use the name parameter
        this.name = "$type $name"
    }

    fun takeDamage(damageTaken: Int) {
        if (!sunk) {
            hullIntegrity -= damageTaken
            println("$name hull integrity = $hullIntegrity")

            if (hullIntegrity <= 0){
                println("Destroyer $name has been sunk")
                sunk = true
            }
        } else {
            // Already sunk
            println("Error Ship does not exist")
        }
    }

    fun shootShell():Int {
        // let the calling code know how much damage to do
        return if (ammo > 0) {
            ammo--
            shotPower
        }else{
            0
        }
    }

...
 

Чего я не вижу или не вижу?

Спасибо за любые советы.

Комментарии:

1. в вашем imports вверху MainActivity я не вижу вашего Destroyer.kt файла. Проверьте, импортировано ли у вас это

2. Кроме того, ваш код находится внутри класса MainActivity , хотя на самом деле он должен быть внутри onCreate метода или любого другого метода, который вам нужно переопределить

3. Вы не можете писать инструкции внутри класса, они должны быть инкапсулированы в функцию, как вы ожидаете, что они будут там? Вероятно, вы хотите поместить их в точку входа (в данном случае onCreate).

4. Спасибо!! Это то, что мне было нужно. Каков синтаксис для импорта класса? import Destroyer.kt ?

Kotlin Discussions

Loading

Skip to content

I am newbie in kotlin, I trying to apply lesson on oop on kotlin, but I got multiple «Expecting member declaration»

enter image description here

I don’t know where’s error in this code

open class Car( open val color:String?=null, open val brand:String?=null) {
    
    open fun speed(){
        println("max speed is 220")
    }
}

class Toyota() : Car() {
    override color = "White"
    override brand = "Toyota"
    
    override fun speed(){
        println("max speed is 360")
    }
}


fun main() {
   
    var car:Toyota = Toyota()
    car.speed()
    
   
}

>Solution :

You are missing a val keyword in both parameters in Toyota class:

class Toyota() : Car() {
    override val color = "White"
    override val brand = "Toyota"

    override fun speed(){
        println("max speed is 360")
    }
}

Or you can do it even better by using Car constructor directly:

class Toyota : Car(color = "White", brand = "Toyota") {
    override fun speed(){
        println("max speed is 360")
    }
}

With this approach you can even make Car simpler (no need for open keyword on your properties):

open class Car(val color : String? = null, val brand : String? = null) {
    open fun speed(){
        println("max speed is 220")
    }
}

I want to assign my class variable in constructor, but I get an error ‘expecting member declaration’

class YLAService {

    var context:Context?=null

    class YLAService constructor(context: Context) {
        this.context=context;// do something
    }
}

Shubham Suryavanshi's user avatar

asked Jun 5, 2017 at 12:15

hugerde's user avatar

1

In Kotlin you can use constructors like so:

class YLAService constructor(val context: Context) {

}

Even shorter:

class YLAService(val context: Context) {

}

If you want to do some processing first:

class YLAService(context: Context) {

  val locationService: LocationManager

  init {
    locationService = context.getService(LocationManager::class.java)
  }
}

If you really want to use a secondary constructor:

class YLAService {

  val context: Context

  constructor(context: Context) {
    this.context = context
  }

}

This looks more like the Java variant, but is more verbose.

See the Kotlin reference on constructors.

answered Jun 5, 2017 at 12:16

nhaarman's user avatar

nhaarmannhaarman

97.9k55 gold badges246 silver badges278 bronze badges

3

I’ll just add some info and give real example. When you want to initialize class && trigger some event, like some method, in Python we can simply call self.some_func() being in __init__ or even outside. In Kotlin we’re restricted from calling simple in the context of the class, i.e.:

class SomeClass {
    this.cannotCallFunctionFromHere()
}

For such purposes I use init. It’s different from constructor in a way that we don’t clutter class schema && allows to make some processing.

Example where we call this.traverseNodes before any further actions are done with the methods, i.e. it’s done during class initialization:


class BSTIterator(root: TreeNode?) {
    private var nodes = mutableListOf<Int>()
    private var idx: Int = 0
    
    init {
        this.traverseNodes(root)
    }
    
    
    fun next(): Int {
        val return_node = this.nodes[this.idx]
        this.idx += 1
        return return_node
    }

    fun hasNext(): Boolean {
        when {
            this.idx < this.nodes.size -> {
                return true
            } else -> {
                return false
            }
        }
    }
    
    fun traverseNodes(node: TreeNode?) {
        if(node!!.left != null) {
            this.traverseNodes(node.left)
        }
        this.nodes.add(node.`val`)
        if(node!!.right != null) {
            this.traverseNodes(node.right)
        }
    }

}

Hope it also helps someone

answered Jan 5, 2022 at 7:09

SleeplessChallenger's user avatar

#android-studio #kotlin

#android-studio #kotlin

Вопрос:

Я изучаю программирование на Android (начальный уровень) и следую руководству. Я получаю сообщение об ошибке при запуске / сборке проекта. Expecting member declaration . Я проверил код на наличие опечаток и синтаксических ошибок. Я погуглил это, но я просто не уверен, что это значит или что искать, чтобы это исправить.

Другие классы, используемые в проекте, автоматически просматриваются классом MainActivity?

Код частично:

 MainActivity.kt:

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }

    val friendlyDestroyer = Destroyer("Invincible")
    val friendlyCarrier = Carrier("Indomitable")

    val enemyDestroyer = Destroyer("Grey Death")
    val enemyCarrier = Carrier("Big Grey Death")

    val friendlyShipyard = ShipYard()

    friendlyDestroyer.takeDamage(enemyDestroyer.shootShell())
    friendlyDestroyer.takeDamage(enemyCarrier.launchAerialAttack())

    // Fight back
    enemyCarrier.takeDamage(friendlyCarrier.launchAerialAttack())
    enemyCarrier.takeDamage(friendlyDestroyer.shootShell())
    ...
 

Любая строка, в которой есть экземпляр класса с вызовом функции, показывает red squiggly line и ошибку.

В строке: friendlyDestroyer.takeDamage(enemyDestroyer.shootShell()) отображается expecting member declaration ошибка практически в каждой части строки.

Это происходит при каждом экземпляре класса, вызывающего класс.

Я не вижу никаких ошибок для других классов / файлов.

 Destroyer.kt:

package com.johndcowan.basicclasses

class Destroyer(name: String) {
    // what is the name of the ship
    var name: String = ""
        private set

    // what type of ship is it
    // alwys a destroyer
    val type = "Destroyer"

    // how much the ship can take before sinking
    private var hullIntegrity = 200

    // how many shots left in the arsenal
    var ammo = 1
      // cannot be directly set externally
      private set

    // no external access whatsoever
    private var shotPower = 60

    // has the ship been sunk
    private var sunk = false

    // this code runs as the instance is being initialized
    init {
        // so we can use the name parameter
        this.name = "$type $name"
    }

    fun takeDamage(damageTaken: Int) {
        if (!sunk) {
            hullIntegrity -= damageTaken
            println("$name hull integrity = $hullIntegrity")

            if (hullIntegrity <= 0){
                println("Destroyer $name has been sunk")
                sunk = true
            }
        } else {
            // Already sunk
            println("Error Ship does not exist")
        }
    }

    fun shootShell():Int {
        // let the calling code know how much damage to do
        return if (ammo > 0) {
            ammo--
            shotPower
        }else{
            0
        }
    }

...
 

Чего я не вижу или не вижу?

Спасибо за любые советы.

Комментарии:

1. в вашем imports вверху MainActivity я не вижу вашего Destroyer.kt файла. Проверьте, импортировано ли у вас это

2. Кроме того, ваш код находится внутри класса MainActivity , хотя на самом деле он должен быть внутри onCreate метода или любого другого метода, который вам нужно переопределить

3. Вы не можете писать инструкции внутри класса, они должны быть инкапсулированы в функцию, как вы ожидаете, что они будут там? Вероятно, вы хотите поместить их в точку входа (в данном случае onCreate).

4. Спасибо!! Это то, что мне было нужно. Каков синтаксис для импорта класса? import Destroyer.kt ?

1) Understand your language syntax

Your tutorial is in Java. You try to write in Kotlin. Java and Kotlin have different syntax and if you reproduce this tutorial word for word in Kotlin, it will fail.

Follow the turorial and write your code in Java. Switch to Kotlin later when you’re more confident with what you’re doing. Focus on one thing at a time.

2) Find views at the right time

The Activity object is instatiated for you by the framework with a public empty constructor. At this time there are no views to be found. If you call findViewById any time before setContentView it will return null and crash if you try to assign it to a non-nullable variable.

The above applies for both Java and Kotlin.

For Java follow the tutorial. It should look something like this:

Toolbar toolbar; // Declare the variable here so it's accessible outside of onCreate.

@Override
public void onCreate(@Nullable final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2); // Inflate view hierarchy.
    toolbar = (Toolbar) view.findViewById(R.id.toolbar); // Find your views.
    setSupportActionBar(toolbar);
}

In Kotlin there are several options.

You can use lateinit modifier which allows you to declare a non-nullable variable but assign it later in onCreate.

lateinit var toolbar: Toolbar

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)
    toolbar = findViewById(R.id.toolbar) as Toolbar
    setSupportActionBar(toolbar)
}


Or you can use lazy delegate. The variable will be assigned when you first access it.

val toolbar: Toolbar by lazy(LayzThreadSafetyMode.NONE) {
    toolbar = findViewById(R.id.toolbar) as Toolbar
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)
    setSupportActionBar(toolbar)
}

Don’t use the delegate. It creates an unnecessary holder object for each lazy, that’s wasteful.

You can also use Kotlin Android Extensions and just access toolbar directly because all of the heavy lifting is done for you.

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)
    setSupportActionBar(toolbar)
}

Alternatively you can use View Binding available since Android Studio 3.6 Canary 11.

private lateinit var binding: ActivityMain2Binding

@Override
fun onCreate(savedInstanceState: Bundle) {
    super.onCreate(savedInstanceState)
    binding = ActivityMain2Binding.inflate(layoutInflater)
    setContentView(binding.root)
    setSupportActionBar(binding.toolbar)
}

You get high performance of the first option and strong type safety on top.

Related videos on Youtube

18CSMP68 || Android Signup & Login Actvity-1/3 || PART-A || PROGRAM-3 || VTU MAD Lab

19 : 33

18CSMP68 || Android Signup & Login Actvity-1/3 || PART-A || PROGRAM-3 || VTU MAD Lab

expecting member declaration android studio java

22 : 33

expecting member declaration android studio java

Android Studio error | cannot resolve symbol 'AppCompatActivity'

01 : 36

Android Studio error | cannot resolve symbol ‘AppCompatActivity’

expecting member declaration android studio java

22 : 23

expecting member declaration android studio java

fix @EActivity (R.layout.activity_main) Missing

05 : 27

fix @EActivity (R.layout.activity_main) Missing

Android Studio - Automatically Change Activity after Few Seconds | Tutorial

03 : 03

Android Studio — Automatically Change Activity after Few Seconds | Tutorial

android studio dependency mismatch Error solution

05 : 17

android studio dependency mismatch Error solution

Solucion a Error en Android Studio - No reconoce las Variables/ID/Boton Unresolved reference: button

04 : 22

Solucion a Error en Android Studio — No reconoce las Variables/ID/Boton Unresolved reference: button

How to show a Toast Message Android Studio Kotlin

04 : 47

How to show a Toast Message Android Studio Kotlin

John’s Android Studio Tutorials

Android Tutorial - Expression Expected Fix

03 : 19

Android Tutorial — Expression Expected Fix

solve jcenter issue in android studio

02 : 26

solve jcenter issue in android studio

StartActivityForResult trong Android và cách xử lý khi bị Deprecated - [Android Tutorial - #53]

21 : 17

StartActivityForResult trong Android và cách xử lý khi bị Deprecated — [Android Tutorial — #53]

startActivityForResult Depreciated Solution |  Android Studio | Java

10 : 13

startActivityForResult Depreciated Solution | Android Studio | Java

Fix startActivityForResult is depricated: alternative solution | How to use ActivityResultLauncher

05 : 45

Fix startActivityForResult is depricated: alternative solution | How to use ActivityResultLauncher

Comments

  • I have been trying to learn through following YouTube tutorials. I am using Android Studio 3.1 Canary and I get to the same point in the tutorials and get stuck. For instance if you go to this YouTube tutorial https://youtu.be/3RMboPhUbmg?t=210 at the 3:30 min mark.

    When they are inputting the MaterialSearchView searchView; it shows up for me with a red underline saying «expecting member declaration» and no matter how many searches I try I cannot find an answer. What is the solution to this error? Thanks

    This is the code contained in the Main2Activity.kt. The result should be calling or knowing the toolbar and materialsearchview objects

    import android.support.v7.app.AppCompatActivity
    import android.os.Bundle
    import android.support.v7.widget.Toolbar
    import com.miguelcatalan.materialsearchview.MaterialSearchView
    import kotlinx.android.synthetic.main.activity_main2.*
    
    class Main2Activity : AppCompatActivity () {
        **MaterialSearchView searchView;**  "expecting member declaration error"
        **Toolbar  toolbar;** "expecting member declaration error"
        Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main2);
            toolbar=(Toolbar()) findViewbyId(R.id.toolbar);
            setSupportActionBar(toolbar);
        }
        *private void searchViewCode()
        {
            searchView=(MaterialSearchView)findViewById(R.id.search_view);
        }
    }
    
    • Welcome to stackoverflow. Please show us a snippet with your code, expected result and error.

  • Don’t do this: val toolbar: Toolbar = toolbar There’s no point, you can already access toolbar. As a bonus Kotlin extensions already include caching of found views.

  • I changed @erafn line of val toolbar: Toolbar = view.findViewById(R.id.toolbar) as Toolbar to this below and it is not showing any red underlines. val toolbar: Toolbar = findViewById(R.id.toolbar) Also the first line in erafn answer worked perfectly.

  • val toolbar: Toolbar will not work because Activity instantiation happens way before onCreate. Since there is no view hierarchy before you call setContentView, toolbar will be null. And because the variable it of type Toolbar (non-nullable) your app will crash on start with a KotlinNullPointerException.

  • You’re correct @Eugen Pechanec, That was a mistake and I’ve removed it

  • I do not think that this is an appropriate answer. Imho, it’s obvious that OP has not a copy/paste-problem (and also an accepted answer with no copy/paste problems at all). This should be a comment instead of an answer.

  • Thanks @ferreiraiso ! I would lose lots of time trying to understand the reason if I didn’t see your answer.

  • fwiw, i had the same issue and this helped me, deleting some whitespace

Recents

Skip to content

I am newbie in kotlin, I trying to apply lesson on oop on kotlin, but I got multiple «Expecting member declaration»

enter image description here

I don’t know where’s error in this code

open class Car( open val color:String?=null, open val brand:String?=null) {
    
    open fun speed(){
        println("max speed is 220")
    }
}

class Toyota() : Car() {
    override color = "White"
    override brand = "Toyota"
    
    override fun speed(){
        println("max speed is 360")
    }
}


fun main() {
   
    var car:Toyota = Toyota()
    car.speed()
    
   
}

>Solution :

You are missing a val keyword in both parameters in Toyota class:

class Toyota() : Car() {
    override val color = "White"
    override val brand = "Toyota"

    override fun speed(){
        println("max speed is 360")
    }
}

Or you can do it even better by using Car constructor directly:

class Toyota : Car(color = "White", brand = "Toyota") {
    override fun speed(){
        println("max speed is 360")
    }
}

With this approach you can even make Car simpler (no need for open keyword on your properties):

open class Car(val color : String? = null, val brand : String? = null) {
    open fun speed(){
        println("max speed is 220")
    }
}

Понравилась статья? Поделить с друзьями:
  • Exploiting roblox ошибка
  • Extreme injector ошибка null
  • F01 ошибка духовой шкаф индезит
  • Extreme injector ошибка kernel32 dll
  • F01 ошибка духовой шкаф miele