Created
August 6, 2022 00:24
-
-
Save syavorsky/09babfc87e4f296ab845db3085f48b91 to your computer and use it in GitHub Desktop.
How do I do this in Java?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Cat { | |
id: number | |
typ: "cat" | |
data: {purrs: boolean} | |
} | |
interface Dog { | |
id: number | |
typ: "dog" | |
data: {barks: boolean} | |
} | |
type Animal = Cat | Dog | |
const animals:Map<number, Animal> = new Map() | |
class Client { | |
getAnimal(id:number):Animal|undefined { | |
return animals.get(id) | |
} | |
addAnimal(a:Animal) { | |
animals.set(a.id, a) | |
} | |
getAnimals():Animal[] { | |
return Array.from(animals.values()) | |
} | |
} | |
const client = new Client() | |
client.addAnimal({id: 1, typ: "cat", data:{purrs: true}}) | |
client.addAnimal({id: 2, typ: "dog", data:{barks: false}}) | |
console.log(client.getAnimals()) | |
// prints | |
// [ | |
// {id: 1, typ: "cat", data:{purrs: true}}, | |
// {id: 2, typ: "dog", data:{barks: false}} | |
// ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment