期待在科特林声明成员 [英] Expecting member declaration in Kotlin

查看:330
本文介绍了期待在科特林声明成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在构造函数中分配我的类变量,但出现错误,期望成员声明

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

}}

推荐答案

在Kotlin中,您可以像这样使用构造函数:

In Kotlin you can use constructors like so:

class YLAService constructor(val context: Context) {

}

更短:

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
  }

}

这看起来更像Java变体,但更冗长.

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

请参见关于构造函数的Kotlin参考.

这篇关于期待在科特林声明成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆