Kotlin抛出NullPointerexception

我开始和Java一起使用Kotlin。 这在java下面的代码。 抛出空指针exception

initFoodQuantitySpinner(); CartDb cartDb = new CartDb(getActivity()); try { P.addToCart(getActivity(), food.getId(), food.getPrice(), foodQuantity); } catch (Exception e) { e.printStackTrace(); } FoodCartModel foodCartModel = new FoodCartModel(new Food(food.getId(), food.getName(), 0, "", "", food.getPrice(), 0, 0, null, "", "", null)); cartDb.insertFood(foodCartModel); if (getActivity() != null) getActivity().invalidateOptionsMenu(); 

下面的代码在Kotlin中抛出空指针exception。

 spinFoodQuantity.visibility = View.VISIBLE val cartDb = CartDb(context) val id = food.id val name = food.name val price = food.price try { P.addToCart(activity, id, price, foodQuantity) } catch (e: Exception) { e.printStackTrace() } val foodCartModel = FoodCartModel( Food(id, name, 0, "", "", price, 0, 0, null!!, "", "", null!!), foodQuantity) cartDb.insertFood(foodCartModel) activity!!.invalidateOptionsMenu() 

添加到购物车function在共享的首选项

  public static synchronized void addToCart(Context context, int id, int price, int quantity) throws JSONException { assurePrefNotNull(context); String data = getCartData(context); JSONArray array; if (data.equals("")) array = new JSONArray(); else array = new JSONArray(data); JSONObject item = new JSONObject(); item.put("id", id); item.put("price", price); item.put("quantity", quantity); array.put(item); prefsEditor.putString(PREF_CART_DATA, array.toString()); prefsEditor.commit(); } 

任何人都可以解释kotlin抛出空指针exception的错误在哪里? 和Android工作室显示关于无法访问的代码警告(下面​​的代码在KOTLIN)

  val foodCartModel = FoodCartModel( Food(id, name, 0, "", "", price, 0, 0, null!!, "", "", null!!), foodQuantity) cartDb.insertFood(foodCartModel) activity!!.invalidateOptionsMenu() 

!! 如果标记的字段为空,则在Kotlin中抛出KotlinNullPointerException。 举个例子:

 var n: String? = null; //changes to n based on whatever; not at all relevant. Should it end up as null afterwards println(n!!)//throw an exception when something is done with it 

如果n为null,会抛出一个exception。

意思是当你null!! 它总是会抛出一个exception,因为null显然是空的,永远不会有实际的值。

而且因为它总是会抛出exception,下面的代码将无法访问。 这是一样的:

 var n: String = "some string" throw RuntimeException();//different exception obviously, but the idea is the same println(n);//unreachable code 

如果你可以有可空的参数,那么把@Nullable添加到Java中的字段或? 在Kotlintypes之后允许参数被保留为空。 我提到了这两个问题,因为在问题中同时包含Java和Kotlin代码,但是您没有添加Food类。 如果你不允许可为null的参数,首先不要传递null。 并明确地不与非null断言

你认为什么是null!! 会做? 用适当的初始化代替这个。