“ Var”必须初始化Kotlin

时间:2020-03-22 17:07:40

标签: java class kotlin methods instance

你们中有些人可以帮助我解决这个小问题吗?我对Kotlin和Android开发非常陌生!我不明白为什么这段代码会向我返回以下错误:

class Catalog {
var musicList: List<Music> = ArrayList()
}

class Music{
    var id: String = ""
}

fun main(args: Array<String>) {  
    var test: Catalog
    test.musicList[0] = "1"  
}

错误:

Variable 'test' must be initialized

怎么了? 谢谢大家!

2 个答案:

答案 0 :(得分:2)

您需要在调用fun main(args: Array<String>) { var test = Catalog() test.musicList[0] = "1" } 的getter之前实例化它:

test

此外,如果您不重新分配val的值,则可以将其声明为fun main(args: Array<String>) { val test = Catalog() test.musicList[0] = "1" }

List

此后,您还会有其他2个错误:

  1. 因为[]是不可变的,所以您不能使用运算符MutableList来赋值

要解决此问题,可以使用List代替class Catalog { val musicList = mutableListOf<Music>() }

fun main(args: Array<String>) {  
    var test = Catalog()
    test.musicList += Music("1")  
}
  1. 您在索引0处没有任何项目,因此您将获得超出范围的异常。 要解决此问题,您可以添加元素:
todoCache: Array<{todoId: string, todo$: ReplaySubject<Todo>}>

getAllRemote(): void { 
    this.http
    .post(URL_GET_TODOS)
    .pipe(
      tap((todo) => {

        this.addTodo(todo)
      })
    );
}

getOneRemote(todoId: string): void {
   this.http
      .post(URL_GET_ONE_TODO, { todoId })
      .pipe(
        tap((todo: Todo) => {
          this.addTodo([todo]);
        })
      );
}

getTodoById(todoId: string): ReplaySubject<Todo> { 
    const cachedTodo = this.todo.find(
      cachedTodo => cachedTodo.todoId === todoId
    );

    if (cachedTodo) {
      return cachedTodo.todo$;
    } else {
      this.chatUses.push({ todoId, todo$: new ReplaySubject(1) });
      this.apiGetChatUseByChatId(chatId, privateChat);
    }
}

addTodo(toAdd: Array<Todo>): void {

      for (let i = 0; i < toAdd.length; i += 1) {
        const index = this.todoCache.findIndex(
          entry => entry.todoId === toAdd[i].id
        );

        if (index === -1) {
          this.chatUses.push({
            todoId: toAdd[i].id,
            todo$: new ReplaySubject(1)
          });
          this.todoCache[this.todoCache.length - 1].todo$.next(toAdd[i]);
        } else {
          this.todo[index].todo$.next(toAdd[i]);
        }
      }
}

答案 1 :(得分:0)

在Kotlin中,您可以通过两种方式初始化变量。

  1. 使用默认值初始化,例如... var temp:String =“”
  2. 使用lateinit关键字初始化(意味着您稍后会初始化),例如... lateinit var temp:String

如果您不使用lateinit,那么您需要使用默认值初始化变量

var test = Catalog()

或者如果您要初始化为空

var test:Catalog? = null