Меню

Expecting member declaration kotlin ошибка

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

96.9k55 gold badges244 silver badges277 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

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

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

1 Answer
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.

init

By clicking «Post Your Answer», you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

#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 ?

Есть чекбокс и кнопка, при включенном чекбоксе должен сменяться активити, при отключенном вылетать тост. Выдается ошибка:

Expecting member declaration

В строках if и else. Просьба подсказать, что не так, т.к. я явно чего-то не понимаю.

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val checkBox = findViewById (R.id.checkBox) as CheckBox
    }
            if (checkBox.isChecked)
                fun gotoActivityTwo(view: View) {
                    val gotoActivityTwo = Intent(this, Main2Activity::class.java)
                    startActivity(gotoActivityTwo)
                }
            else
                fun showToast(view: View) {
                    val toast = Toast.makeText(applicationContext,
                            "Так не пойдет, хитрюга :)",
                           Toast.LENGTH_SHORT)
                    toast.setGravity(Gravity.CENTER, 0, 0)
                    toast.show()
                }
}

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Expected sub function or property ошибка
  • Expected string or bytes like object python ошибка