return 一个 Int 函数如何成为 if 语句的一部分?
How a function that return an Int can be part of if statement?
我定义了一个新函数(请不要参考逻辑,仅在必要时参考):
operator fun Int?.compareTo(other: Int): Int
{
if (this == null)
return -1
if (this > other)
return 1
else return 0
}
现在在我写的 if 语句中:
val x:Int? =8
if(... && .... && ...&& x > 5)
我看到 x>5 运行我上面写的函数 (compare),但是这个函数没有 return 一个布尔值,它 return 是一个整数。那么,尽管其中一个条件不是布尔值,它如何编译?
在kotlin docs(页尾)中,可以看到a > b
使用了compareTo,但实际上翻译成a.compareTo(b) > 0
。
所以 if(... && x > 5)
是隐含的 if(... && x.compareTo(5) > 0)
,这就是为什么你可以在 if 语句中使用它
我定义了一个新函数(请不要参考逻辑,仅在必要时参考):
operator fun Int?.compareTo(other: Int): Int
{
if (this == null)
return -1
if (this > other)
return 1
else return 0
}
现在在我写的 if 语句中:
val x:Int? =8
if(... && .... && ...&& x > 5)
我看到 x>5 运行我上面写的函数 (compare),但是这个函数没有 return 一个布尔值,它 return 是一个整数。那么,尽管其中一个条件不是布尔值,它如何编译?
在kotlin docs(页尾)中,可以看到a > b
使用了compareTo,但实际上翻译成a.compareTo(b) > 0
。
所以 if(... && x > 5)
是隐含的 if(... && x.compareTo(5) > 0)
,这就是为什么你可以在 if 语句中使用它