Using a Class Object in Case Statement

Using a class object in case statement

I wouldn't use to_s, because "String".to_s would be "String", so maybe I'd do

case
when a == String then ...
when a == Fixnum then ...
end

or

a = String

case [a]
when [String] then puts "String"
when [Array] then puts "Array"
end

Case Switch Statement with Class Object in Scala

Why not simply do the obvious:

def foo(c: Class[_]): Unit = {
if (c == classOf[Map[_, _]]) println("do Map things")
else if (c == classOf[String]) println("do string things")
else println("do sth. else") }
}

You could rewrite it as a match-expression using if-guards:

c match {
case x if x == classOf[Map[_, _]] => ...
...
}

but this doesn't seem any shorter or clearer. Also note: you can't tell a Map[Int, Double] and a Map[String, String] apart at runtime because of the type erasure.

Case statement for class objects

Something more functional?

is_descendant = lambda { |sample, main| main <= sample }
not_a_class = lambda { |x| !x.kind_of?(Class) }

mine = Fixnum

case mine
when not_a_class then raise 'Not a class' # Credits to @brymck
when is_descendant.curry[Float] then puts 'Float'
when is_descendant.curry[Integer] then puts 'Integer'
else raise 'Shit happens!'
end

# ⇒ Integer

How to use class member function of an object on different switch case statement?

You can use a unique pointer:

#include <iostream>
#include <memory>
#include <vector>
using std::cin;
using std::cout;
using std::endl;

class Diagonal {
private:
std::vector<int> A;
public:
Diagonal() : A(2) {};
Diagonal(int n) : A(n) {}

void Create() {
cout<<"Enter the Elements : ";
for(std::size_t i = 0; i < A.size(); ++i) {
cin >> A[i];
}
}
void Set(std::size_t i, std::size_t j, int x){
if(i==j){
A[i-1] = x;
}
}
int Get(std::size_t i, std::size_t j) {
if(i == j){
return A[i-1];
}
return 0;
}
void display() {
for (std::size_t i = 0; i < A.size(); ++i) {
for (std::size_t j = 0; j < A.size(); ++j) {
if (i == j) {
cout << A[i] << " ";
} else {
cout<<"0 ";
}
}
cout << endl;
}
}
};

void functionName(){
cout<<"----- Functions ------"<<endl;
cout<<"1. Create "<<endl;
cout<<"2. Get "<<endl;
cout<<"3. Set "<<endl;
cout<<"4. Display "<<endl;
cout<<"5. Exit "<<endl;
}

int main(){
int ch;
do {
cout << "------ Menu --------" << endl;
cout << "1. Diagonal " << endl;
cout << "2. Lower Tri-angular " << endl;
cout << "3. Upper Tri-angular " << endl;
cout << "4. Tri-diagonal" << endl;
cout << "5. Toplitz" << endl;
cout << "6. Exit" << endl;
cout << endl;
cin >> ch;
int fun;
switch (ch) {
case 1: {
auto d = std::make_unique<Diagonal>();
do {
functionName();
cin >> fun;
switch (fun) {
case 1:
cout << "Enter the size of matrix : ";
std::size_t n;
cin >> n;
d = std::make_unique<Diagonal>(n);
d->Create();
break;
case 2:
//how to call d.get();
//d->Get();
break;
case 3:
//how to call d.set();
//d->Set();
break;
case 4:
//how to call d.display();
d->display();
break;
case 5:
break;
}
} while (fun <= 4);
break;
}
case 2:
functionName();
break;
case 3:
functionName();
break;
case 4:
functionName();
break;
case 5:
functionName();
break;
}
} while (ch <= 5);
return 0;
}

How to pass an object from one case statement to another

declare a HockeyPlayer instance outside of switch statement like this:

HockeyPlayer player = null;  
do{
System.out.println(MENU);
choice = input.nextLine();
switch(choice){
case "A":
player = new HockeyPlayer();
players[player.getPlayerNumber()-1] = player;
break;
case "G":
player.addGameDetails(); //invoke the method here for case G
break;
case "S":
break;
case "X":
}

}while(!choice.equals("X"));
}

The idea is that HockeyPlayer object should be accessible to all the switch statements so you need to declare it somewhere where it is accessible.

Ruby class types and case statements

You must use:

case item
when MyClass
...

I had the same problem:
How to catch Errno::ECONNRESET class in "case when"?

Return different object types in case statement?

The easiest way to tackle this would be to use an interface (in my mind):

using System;

namespace Test
{
public class Test
{
public IVehicle CreateObjectType(JToken token)
{
switch(token["type"].Value<string>())
{
case "Car":
return new Car();

case "Boat":
return new Boat();

default:
throw new NotImplementedException();
}
}
}

public class Boat : IVehicle { }

public class Car : IVehicle { }

public interface IVehicle { }
}

Alternatively, you could do some form of inheritance chain and use generics.

Additional: Documentation on Interfaces

Can a switch statement be used to determine the class of an object?

For a switch to work the value must be a primitive value, a String or an Enum value.
In OO code switch statements are something of a code smell; generally indicating you have missed a chance to use polymorphism.

In functional languages you might be able to use a case statement to do what your are trying.

Java is OO so I would make use of polymorphism, you will have a cleaner design.

Polymorphism
Is an OO concept that basically says that two objects/classes can be considered to "BE" the same if one is the super set of the other. That is, if the objects/classes satisfy the IS-A relationship.
For example if you have a Car class, FastCar and VintageCar classes that extend Car both FastCar and VintageCar are Car classes and thus satisfy the IS-A relationship, and thus they can be used any where in code where Car can be called.
The implication here is that if Car...accelerate exists then FastCar.accelerate exists and can have different characteristics from VintageCar.accelerate so when call accelerate the code doesn't need to know the subtype but will call the correct accelerate method.



Related Topics



Leave a reply



Submit