Last active
June 9, 2018 17:45
-
-
Save HCLarsen/8f96f55ea578fa60853d86812ee2fffa to your computer and use it in GitHub Desktop.
Basic demonstration of what can be done with Crystal Generic classes
This file contains hidden or 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
class Gen(T) | |
getter value : T | |
def initialize(@value : T) | |
end | |
def self.build(value : K) : Gen(K) forall K | |
Gen(K).new(value) | |
end | |
def type : Class | |
T | |
end | |
def test : T | |
value | |
end | |
end | |
gen1 = Gen.build("Foo") | |
gen2 = Gen.build(1) | |
gen1.test.class | |
gen2.test.class | |
class SpecString < Gen(String) | |
end | |
class SpecInt < Gen(Int32) | |
end | |
class Container(T) | |
def initialize(@gen : Gen(T)) | |
end | |
def type : Class | |
T | |
end | |
end | |
con1 = Container.new(SpecInt.new(1)) | |
con2 = Container.new(SpecString.new("String")) | |
con1.type | |
con2.type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment