Skip to content

Instantly share code, notes, and snippets.

@emmiep
Created November 20, 2019 13:33
Show Gist options
  • Save emmiep/d089917d75628830ddf40ed44a4e3819 to your computer and use it in GitHub Desktop.
Save emmiep/d089917d75628830ddf40ed44a4e3819 to your computer and use it in GitHub Desktop.
Using typeof with instance methods in Crystal
require "json"
class Container(T)
getter value : T
def initialize(@value)
end
end
def new_container(json : String, t_class : T.class) : T forall T
value = typeof(T.allocate.value).from_json(json)
T.new(value)
end
alias Int32Container = Container(Int32)
container = new_container("123", Int32Container)
puts container.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment