Skip to content

Instantly share code, notes, and snippets.

@syavorsky
Created August 6, 2022 00:24
Show Gist options
  • Save syavorsky/09babfc87e4f296ab845db3085f48b91 to your computer and use it in GitHub Desktop.
Save syavorsky/09babfc87e4f296ab845db3085f48b91 to your computer and use it in GitHub Desktop.
How do I do this in Java?
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