How do I check type of an object in a switch/case?

后端 未结 3 2095
旧巷少年郎
旧巷少年郎 2020-12-19 01:36

I see in examples this code:

if (obj is User) { // do something }

I want to check the type of the object in a switch/case flow, and found a

3条回答
  •  清酒与你
    2020-12-19 02:08

    You can create a condition beforehand. Here is an example, as I bumped into this too:

    String grade;
    
    if(grade is String) {
      grade = grade;
    } else {
      grade = null.toString();
    }
    
    switch(grade) {
      case "A":
        print("Good");
        break;
      case "B":
        print("Nice");
        break;
      case "null":
        print("Type a string");
        break;
      default:
        print("failed");
        break;
    }
    

    This way you can check if a value is present or it is an empty string. As mentioned above the easy part is to use a simple If - Else, but otherwise use this.

提交回复
热议问题