强制将null转换为非null类型 [英] Force a null into non-nullable type
问题描述
是否可以通过某种我知道自己在做什么"将null塞入不可为null的类型中?
Is there a way to jam a null into a non-nullable type with some sort of "I know what I'm doing"?
我想创建一个双向链接列表:
I want to make a doubly linked list:
data class Node(var prev: Node, var next: Node, val value: Int)
我可以保证,在添加第一个节点之后但在第二个节点之前,此列表在初始化期间始终会至少有两个元素 .我想保证prev和next永远不会为空.
I can guarantee that this list will have at least two elements at all times except during initialization, after the first node has been added but before the second node. I'd like to make the guarantee that prev and next will never be null.
我想尝试的一件事是编写一个特殊的构造函数来初始化第一个和第二个节点constructor(v1: Int, v2: Int) : this(Node(this, this, v1), v2)
,但这是行不通的,因为在进入主体之前我无法对this
做任何操作
One thing I thought I'd try is to write a special constructor that initializes both the first and second nodes constructor(v1: Int, v2: Int) : this(Node(this, this, v1), v2)
, but that doesn't work because I can't do anything with this
before entering the body.
推荐答案
I'm wondering if we're doing the same adventofcode puzzle in kotlin
我使用了Lateinit属性来允许大理石更改其在链表中作为节点的位置
I used lateinit properties to allow the marble to change its position as a node in a linked list
class Marble(val marbleNumber: Long) {
lateinit var counterClockwiseMarble: Marble
lateinit var clockwiseMarble: Marble
}
最初是二传手
class Marble(val marbleNumber: Long) {
lateinit var counterClockwiseMarble: Marble
private set
lateinit var clockwiseMarble: Marble
private set
fun setCounterClockwise(m: Marble) {
this.counterClockwiseMarble = m
}
fun setClockwise(m: Marble) {
this.clockwiseMarble = m
}
}
但是当使用受到足够控制以确保安全时,这似乎是很多文字
but that seemed like a lot of text when usage was controlled enough to be safe
如果是同样的难题,则可以在github上的上下文中查看此内容
If it is the same puzzle you can see this used in context on github
这篇关于强制将null转换为非null类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!