为什么在Kotlin中调用null值时,toString会抛出异常?

时间:2018-03-12 14:39:43

标签: kotlin kotlin-null-safety

给出代码

fun main(args: Array<String>) {
    val someText: String? = null
    println(someText.toString())
}

运行时,输出

null

出现两个问题:

  • 是可以实现自定义的null-safe方法,并回退到某些默认代码(比如,我认为toString会这样做)
  • 为什么没有抛出异常?

1 个答案:

答案 0 :(得分:2)

来自docs

fun Any?.foo() = println(this ?: "Sadly, this is null")

fun main(args: Array<String>) {
    val x: Int? = null
    val y: Int? = 3

    x.foo()       // "Sadly, this is null"
    y.foo()       // "3"
    null.foo()    // "Sadly, this is null"
}
     

返回对象的字符串表示形式。可以使用null接收器调用,在这种情况下,它返回字符串“null”。

您可以通过编写extension function来实现类似的行为。例如:

const getUserExchangeAccountDetails = function(props, params, callback) {
const client = new bittrex(constants.bittrexApiKey, constants.bittrexSecretKey);
let responseArray = [];
let tempArr = [];
let otherArr = [];
let coinNumber = 0;

return new Promise(function(resolve, reject) {
    client.getbalances(function (err, response, taskcallback) {
        if (err) {
            reject(err);
        } else {
            let coinsList = response.result;
            console.log("Results-----", response.result);

            for(let i = 0; i < response.result.length; i++ ){
                let coin = {
                        currency : "",
                        balance : 0,
                        usdPrice : 0,
                        coinsInUsd : [],
                        totalCoins : 0,
                };

                if(response.result[i].Currency != null || 
                    response.result[i].Currency != ""){
                        coin.currency = response.result[i].Currency;
                }

                if(response.result[i].Balance > 0 ){
                    coin.balance = response.result[i].Balance;
                }

                if(coin.currency != "" && coin.balance > 0){
                        coinNumber = coinNumber + 1;
                        coin.totalCoins = coinNumber;
                        if (coin.currency != 'BTCP') {
                            currenciesService.getCurrencyLatestInfo(coin.currency).then((data) => {
                                coin.usdPrice = data;
                                let usdData = conversionIntoDollar.coinsConversionInUsd(coin.balance, coin.usdPrice);
                                coin.coinsInUsd.push(usdData);
                            });
                        }
                        responseArray.push(coin);
                        console.log(responseArray);

                }
            }
            resolve(responseArray);  
        } //else
    });
})

<子> Live example.