![](/img/trans.png)
[英]is there a way for me to fix the " Assignments are not expressions, and only expressions are allowed in this context" in this kotlin
[英]Kotlin assignments are not expressions. Any other way to force assertions to be enabled?
我目前正在學習Kotlin,而我做的一種方法是自動將Java代碼轉換為Kotlin並研究結果。 我嘗試轉換的一段Java代碼是試圖確保啟用斷言的類中的以下靜態塊:
static {
boolean assertsEnabled = false;
assert assertsEnabled = true;
if (!assertsEnabled)
throw new AssertionError("Please enable assertions!");
}
這依賴於assertsEnabled = true
表達式作為assert
的參數。 在Java中,賦值是表達式。 在Kotlin中,它們不是,因此無法進行轉換。 還有其他方法嗎?
不幸的是,Kotlin沒有具有特殊語義的assert
關鍵字。 相反,它具有以下功能:
inline fun assert(value: Boolean, lazyMessage: () -> Any)
您可以看到作為第一個參數傳遞的表達式是無條件求值的。 這意味着您無法實現與Java中相同的輕量級檢查。 您必須觸發實際的斷言失敗才能確保。
因此,您需要按照@Zoe
建議進行@Zoe
:
try {
assert(false)
throw IllegalStateException("Please enable assertions!")
} catch (e: AssertionError) {
// Things are looking good; carry on
}
如果您堅持拋出AssertionError
而不是IllegalStateException
,則可以為此使用一個布爾變量。
var assertionsAreDisabled = false
try {
assert(false)
assertionsAreDisabled = true
} catch (e: AssertionError) {
// Things are looking good; carry on
}
if (assertionsAreDisabled) {
throw AssertionError("Please enable assertions!")
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.