你们中有些人可以帮助我解决这个小问题吗?我对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
怎么了? 谢谢大家!
答案 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个错误:
[]
是不可变的,所以您不能使用运算符MutableList
来赋值要解决此问题,可以使用List
代替class Catalog {
val musicList = mutableListOf<Music>()
}
。
fun main(args: Array<String>) {
var test = Catalog()
test.musicList += Music("1")
}
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中,您可以通过两种方式初始化变量。
如果您不使用lateinit,那么您需要使用默认值初始化变量
var test = Catalog()
或者如果您要初始化为空
var test:Catalog? = null