Skip to content

Instantly share code, notes, and snippets.

@Craftist

Craftist/.baila Secret

Created June 21, 2021 17:26
Show Gist options
  • Save Craftist/fc6d6e25256786142a5b344717eddb28 to your computer and use it in GitHub Desktop.
Save Craftist/fc6d6e25256786142a5b344717eddb28 to your computer and use it in GitHub Desktop.
`object interface` defines a name (MyOI in this case)
that can be used to structurally type any object (like in Go or TypeScript)
(reminder: Baila is a nominally typed language, like Java, C# or C++)
```baila
object interface MyOI {
x: Int
y: String
z : <Int>Function # <Int>Function = () -> Int
}
var obj1: MyOI = object {
var x: Int = 123
var y: String = "Hello world"
function z : Int { return 456 }
}
# obj1 is a valid MyOI
var obj2: MyOI = object {
var x: Int = 123
function z : Int { return 456 }
}
# obj2 is not a valid MyOI: "y: String" is missing
var obj3: MyOI = object {
var x: Int = 123
var y: String = "Hello world"
function z : Int { return 456 }
var w: Boolean = true
function f(i: Int) : Int = i * 2
}
# obj3 is a valid MyOI: you can have more members,
# you just have to have x, y and z
class MyClass { var x: Int = 123; var y: String = "Suka"; function z: Int { return 1337 } }
var obj4: MyOI = MyClass()
# obj4 is a valid MyOI even though it's an instance of MyClass
class MyClass2 { var x: Int = 123; var y: String = "Suka"; function z: Int { return 1337 }; function huy { } }
var obj5: MyOI = MyClass2()
# obj5 is a valid MyOI even though it's an instance of MyClass2
```
Clarification: all obj1..4 from the above can only be set to
the variables/parameters/fields/etc of type MyOI
because there is no guarantee that, all members are present
Hypothetical example:
```baila
var testMyOIObject: MyOI = MyClass() # success
var testMyClassObject: MyClass = testMyOIObject # invalid in Baila,
# but hypothetically could work
var testMyClass2Object: MyClass2 = testMyOIObject # ALERT ACHTUNG
```
If we allowed to set instances of object interfaces to classes,
this would crash since there is no guarantee that MyClass instance (which testMyOIObject is)
has a "huy" function, which it's lacking, so testMyClass2Object.huy() would fail
Therefore lines 74, 75 and 77 are illegal in Baila.
You still can insert object interfaces into other object interfaces as long as they are compatible.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment