Create object using Class(Class Name)
object ThreadAndRunnable {
def main(args: Array[String]): Unit = {
val strCat :String = "Cat"
//....I have to create object for Cat but I have a String "Cat".
}
}
class Animal{
def eat() = println("I Am Animal, I can Eat Anything")
}
class Cat extends Animal{
override def eat(): Unit = println("I am Cat, I eat Fish")
}
I have to create an object for Cat, but I have a String "Cat". How to create an object using the String "Cat"?
do you know?
how many words do you know
See also questions close to this topic
-
There is any objective reason why Scala differentiate fold and reduce functions?
Reduce can be an override fold that doesn't take the first element. I guess there is an answer to that design decision but I can't find it.
-
Scala argument upper type bounds and overriding
I am trying to understand and incorporate upper bound types with overriding in my system, but have not been able to achieve it without some ugly code. I have the following 2 traits:
trait MyId { def getType: Int // For simplicity. This is Enum/Object in code. def id: Any } trait MyTrait { protected def supportedType: Int def doSomething(id: MyId): Unit = { if (id.getType == myType) doSomethingInternal(id) } protected def doSomethingInternal(id: _ <: MyId): Unit }
and I want to create subtypes as:
class X(x: Long) extends MyId { override def getType: Int = 1 override def id: Long = x } class Y(y: String) extends MyId { override def getType: Int = 2 override def id: String = y } class A extends MyTrait { override protected def supportedType: Int = 1 override protected def doSomethingInternal(id: X): Unit {...} } class B extends MyTrait { override protected def supportedType: Int = 2 override protected def doSomethingInternal(id: Y): Unit {...} }
However, this does not work. The workaround I have been using is to use
asInstanceOf[]
:class A extends MyTrait { override protected def supportedType: Int = 1 override protected def doSomethingInternal(id: MyId): Unit { val id2 = id.asInstanceOf[X] } } class B extends MyTrait { override protected def supportedType: Int = 2 override protected def doSomethingInternal(id: MyId): Unit { val id2 = id.asInstanceOf[Y] } }
Is there a way I can get rid of the
asInstanceOf[]
?EDIT
Further more, I have the following processor which requires calling the correct
MyTrait
subclass based on the givenMyId.getType
:def process(ids: Seq[MyId], processors: Map[Int, MyTrait]): Unit = { ids.foreach{ id => processors.get(id.getType).doSomething(id) } }
Edit 2:
getType
isInt
for simplicity here. This is actually an enum/object in my code.- Renamed
getSomething
todoSomething
for more clarity.
-
Spark: retrieving old values of rows after casting made invalid input nulls
I am having trouble retrieving the old value before a cast of a column in spark. initially, all my inputs are strings and I want to cast the column num1 into a double type. However, when a cast is done to anything that is not a double, spark changes it to null.
Currently, I have dataframes
df1:
num1 unique_id 1 id1 a id2 2 id3 and a copy of df1: df1_copy where the cast is made.
when running
df1_copy = df1_copy.select(df1_copy.col('num1').cast('double'), df1_copy.col('unique_id'))
it returns df1_copy:
num1 unique_id 1 id1 null id2 2 id3 I have tried putting it into a different dataframe using select and when but get an error about not being able to find the column num1. The following is what I tried:
df2 = df1_copy.select(when(df1_copy.col("unique_id").equalTo(df1.col("unique_id")),df1.col('num1)).alias("invalid"), df1_copy.col('unique_id'))
-
Read each name in Array list to create seperate object for
I have a file that has student names, age, and an id number. I have a student class that holds the everything above for each student object. I stored all the names, id numbers. and age separately in an array list. Now im trying to assign the info to create a student object.
public class Student { private String lName; private int idNumber; private int age; public Student() { lName = ""; idNumber = 0; age = 0; } public Student(String l, int i, int a) { lName = l; idNumber = i; age = a; } public void setName(String last) { lName = last; } public String getName() { return lName; } public void setIdNum(int num) { idNumber = num; } public int getIdNum() { return idNumber; } public void setAge(int a) { age = a; } public int getAge() { return age; } }
My Text File looks something like this: This info is stored in parallel array lists. I don't quite get how to implement this into an object to pass it into my second contractor method.
Josh 2134 19 Smith 5256 21 Rogers 9248 19 Andrew 7742 20
Here's what I've tried;
public static void main(String[] args) { String file = "studentData.txt"; Scanner reader = new Scanner(file); ArrayList<String> lastNames = lNames(file); ArrayList<Integer> idNumbers = idNum(file); ArrayList<Integer> ageList = ages(file); Scanner input = new Scanner(System.in); Student s1 = new Student(); // confused about how to implement this constructor with the textile info for (int i = 0; i<idNumbers.size(); i++) { Student user = new Student(lastNames.get(i), idNumbers.get(i), ageList.get(i)); } //user enters idNumber to display age System.out.println("Enter ID Number"); //exception handling to be added int idNum = input.nextInt(); for (int i = 0; i<idNumbers.size(); i++) { if (idNum == idNumbers.get(i)) { s1.setAge(ageList.get(i)); System.out.println(s1.getAge()); } } }
-
Custom utility types (generic types) for classes `IsClass` of TypeScript
I am trying to create a
generic type
to make sure the first parameter to be a class. However, the factory function parameter cannot be replaced by ageneric type
.The following upper parts were my attempts. The last part were a working example that directly write the
extends ...
which worked.Why does it works inside a function, but not works as a
generic type
IsClass
?class A { constructor() { } } class B {} class C extends B {} // ERRORS: type IsClass<T extends new (...args: any) => InstanceType<T>> = T type IsClass2<T> = T extends new (...args: any) => InstanceType<T>? T: never type X = IsClass<A> type Y = IsClass2<A> function someFactoryError<T>(clx: IsClass<T>) { return new clx() } someFactoryError(A) function someFactoryError2<T>(clx: IsClass2<T>) { return new clx() } someFactoryError2(A) // WORKS: function someFactoryWorks<T extends new (...args: any) => InstanceType<T>>(clx: T) { return new clx() } const a0 = someFactoryWorks(A) const b0 = someFactoryWorks(B)
Related:
-
Nested list in C# with layers
I am not an expert coder and I have just started learning about Generic data types. What I am trying to code is a List inside of a list inside of a list .
For example- at the first level - I want numbers each inside of a list
Layer 1 list1=[1,2,3,4,5,6,7,8,9,10......1000] ,
At the 2nd layer I'd like list from 1st layer added as an element to a parent list 2 when layer 1 meets certain condition- ex layer 1 reaches max=10
List2=[List1[0:10],List1[10:20],List1[20:30], .....] ,
At layer 3, i'd like to repeat the process, all elements of layer 2 get added as an element to a new parent list 3 when layer 2 meets a max condition. list3[0]=[list2[0:10],list2[10:20],list2[20:30]..... and so on.
Only the first layer would have integer values, the successive layer would be a wrapping of it's the previous layer. How can I code this in C#?
Thanks!
-
How to convert String having key=value pairs to Json
myString =
{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00};
I want to convert it to the following string.
{"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};
How can I do it in java?
-
VBA: Creating a class property that is an array of dictionaries
In Microsoft Excel VBA I need to create a class that has two properties, "Name" and "Holdings". "Name" is just a string so the code for that is easy. But I need "Holdings" to be a variable length array containing dictionary objects. So this is what I wrote:
Private mName As String Private mHoldings() As Scripting.Dictionary Public Property Let Name(vName As String) mName = vName End Property Public Property Get Name() As String Name = mName End Property Public Property Set Holdings(vHoldings() As Scripting.Dictionary) Set mHoldings = vHoldings End Property Public Property Get Holdings() As Scripting.Dictionary Set Holdings = mHoldings End Property
When I try to compile it gives me this error: "Definitions of property procedures for the same property are inconsistent, or property procedure has an optional parameter, a ParamArray, or an invalide Set final parameter.
What I doing wrong?
-
How to access an object inside another object in a map in react
react.js is complicated sometimes, I'm trying to access an information of a state, I have an array which has one object inside, and in this object, there is another object called price, and in this last object there is one property called price too, and when I try to get this information in a map function, the code breaks, this is my map code: (the error line is in ******) the error show like this: Uncaught TypeError: Cannot read properties of undefined (reading 'price')
products.map((item) => { return ( <MainContainer onMouseEnter={() => onEnter(item.id)} key={item.id}> <Card> <TopContainer> <p>163892</p> <h2>{item.name}</h2> <Icons> <svg clip-rule="evenodd" fill-rule=</svg> <InfoOutlinedIcon/> </Icons> </TopContainer> <hr/> <MidContainer> <img src='https://cfarma-public.s3-sa-east-1.amazonaws.com/images/nexfar-product-default-image.jpg'/> <div> <p>Base</p> ****************************************<p>Nexfar<br/>R${item.price.price}</p>******************** </div> <div></div> <div></div> <div></div> <div></div> </MidContainer> </Card> </MainContainer> ); })
this image shows how the objects structure is
Thank you guys!