Why is there an error: type mismatch in my code? - type-mismatch

class Club(val name: String, val stadium: String) {
// Produces a textual description of the club (which consists of just the club's name).
override def toString = this.name
}
class Match(val home: String, val away: String) {
...
}
val match1 = new Match(club2, club1)
Why doesn't val match1 work?

Related

How to dynamically instantiate a class (Function.apply for class)?

In Dart, I can dynamically call a function using Function.apply:
Function.apply(foo, [1,2,3], {#f: 4, #g: 5});
gives exactly the same result as
foo(1, 2, 3, f: 4, g: 5).
Question: Does a similar thing exist for instantiating classes?
Expected result would look something like:
class foo {
final String boo;
int? moo;
foo({required this.boo, this.moo})
}
...
var params = {boo: 'A string value', moo: 121};
Class.apply(foo, params);
// Gives the result:
foo(boo: 'A string value', moo: 121);
Function.apply isn't type-safe, so you should avoid using it if you can.
If you really want to use it with a constructor, you can use it with constructor tear-offs (added in Dart 2.15), which are just Functions:
class Foo {
final String boo;
int? moo;
Foo({required this.boo, this.moo});
#override
String toString() => 'Foo(boo: "$boo", moo: $moo)';
}
void main() {
var params = {#boo: 'A string value', #moo: 121};
var result = Function.apply(Foo.new, [], params);
print(result); // Prints: Foo(boo: "A string value", moo: 121)
}
As far as I know, you can make use of static methods if you want to create an instance without using another instance. Here is a sample:
class Foo {
final String boo;
final int moo;
Foo({this.boo, this.moo});
static fromValues({String boo, int moo}) {
return Foo(boo: boo, moo: moo);
}
}
void main() {
var params = {#boo: 'A string value', #moo: 121};
var fooObject = Function.apply(Foo.fromValues, [], params);
print(fooObject);
print(fooObject.boo);
print(fooObject.moo);
}
Another way is to add 'call' function to class to make it's objects callable and use an object of the class to create new objects. Here is a sample:
class Foo {
final String boo;
final int moo;
Foo({this.boo, this.moo});
call({String boo, int moo}) {
return Foo(boo: boo, moo: moo);
}
}
void main() {
Foo aFoo = Foo(boo: 'nothing', moo: 0);
var params = {#boo: 'A string value', #moo: 121};
var fooObject = Function.apply(aFoo, [], params);
print(fooObject);
print(fooObject.boo);
print(fooObject.moo);
}

Map generic type to record using pattern matching

I've a Union type like this:
type AccountOpenened =
{ Owner: string
AccountId: Guid
CreatedAt: DateTimeOffset
StartingBalance: decimal }
type AccountClosed = { AccountId: Guid }
type AccountEvent = AccountOpenend | AccountClosed
I also have a 3rd party library from which I can get IReadOnlyList<IEvent> whereas IEvent as this signature:
public interface IEvent {
object Data { get; }
}
The library also provides a generic class Event<T> which has this signature:
public class Event<T> : IEvent {
public T Data { get; set; }
}
What I'm trying to achieve is to map an instance of IReadOnlyList<IEvent> to an AccountEvent list using exhaustive pattern matching.
I tried something like this:
let map (input: IEvent): AccountEvent =
match input with
| :? (Event<AccountOpened>) as e ->
{ Owner = e.Data.Owner
AccountId = e.Data.AccountId
CreatedAt = e.Data.CreatedAt
StartingBalance = e.Data.StartingBalance }
| :? (Event<AccountClosed>) as e ->
{ AccountId = e.Data.AccountId }
| _ -> failwith "Unknown Event"
This doesn't work because I get this compiler error:
This expression was expected to have type 'AccountEvent' but here has type 'AccountCreation'
What am I doing wrong here?

Dart - How to initialize List of objects as a private Class member?

In Dart, how can I initialize a List of objects as a private class member?
Here is my Dartpad Link.
Here is my sample code.
// on dartpad: https://dartpad.dev/cfded55df52dd2bb37228d12c7ef049c
void main() {
Co co = Co();
print(co.getTag1()); //Out: profitable
print(co.getMgr1().fn); //Out: null
}
class Co {
List<String> _tags = ['profitable', '1999', 'public', 'NYSE'];
String getTag1() {
return _tags.first;
}
List<Mgr> _mgrs = List.from([
Mgr(
fn: 'Janice',
ln: 'Brown',
),
Mgr(
fn: 'Laura',
ln: 'Lopez',
),
Mgr(
fn: 'Linda',
ln: 'Oakley',
),
], growable: false);
Mgr getMgr1(){
return _mgrs.first;
}
}
class Mgr {
String fn;
String ln;
Mgr({String fn, String ln});
}
Specifically, how can I get the Output of Main >> print(co.getMgr1().fn); to be "Janice"? Thanks.
You are not storing the values passed in your constructor in the fields of Mgr, so the inputs are not being stored anywhere.
Change class Mgr to
class Mgr {
String fn;
String ln;
Mgr({this.fn, this.ln});
}
OR
class Mgr {
String fn;
String ln;
Mgr({String fn, String ln}) {
this.fn = fn;
this.ln = ln;
}
}
This stores the passed arguments in the fields of the class so that they can be accessed later.
Your initialization of the List is perfectly fine in this case.

How to convert a GLib.Value of type GStrv (string[]) to a GLib.Variant

In the following example one class property is of type Gstrv.
With ObjectClass.list_properties() one can query the Paramspec of all properties, and with get_property() all properties can be requested as GLib.Value. How would I access the Value of type GStrv and convert it to a GLib.Variant?
My GLib version is slightly outdated, so I do not have the GLib.Value.to_variant() function available yet :( .
public class Foo: GLib.Object {
public GLib.HashTable<string, int32> bar;
public Foo() {
bar = new GLib.HashTable<string, int32>(str_hash, str_equal);
}
public string[] bar_keys { owned get { return bar.get_keys_as_array(); } }
}
int main() {
var foo = new Foo();
Type type = foo.get_type();
ObjectClass ocl = (ObjectClass) type.class_ref ();
foreach (ParamSpec spec in ocl.list_properties ()) {
print ("%s\n", spec.get_name ());
Value property_value = Value(spec.value_type);
print ("%s\n", property_value.type_name ());
foo.get_property(spec.name, ref property_value);
// next: convert GLib.Value -> GLib.Variant :(
}
foo.bar.set("baz", 42);
return 0;
}
Output:
bar-keys
GStrv
Using GLib.Value.get_boxed() seems to be working.
Example:
// compile simply with: valac valacode.vala
public class Foo: GLib.Object {
public GLib.HashTable<string, int32> bar;
public Foo() {
bar = new GLib.HashTable<string, int32>(str_hash, str_equal);
}
public string[] bar_keys { owned get { return bar.get_keys_as_array(); } }
}
public Variant first_gstrv_property_as_variant(Object obj)
{
Type class_type = obj.get_type();
ObjectClass ocl = (ObjectClass) class_type.class_ref ();
foreach (ParamSpec spec in ocl.list_properties ()) {
print ("%s\n", spec.get_name ());
Value property_value = Value(spec.value_type);
print ("%s\n", property_value.type_name ());
obj.get_property(spec.name, ref property_value);
// next: convert GLib.Value -> GLib.Variant
if(property_value.type_name () == "GStrv") {
return new GLib.Variant.strv((string[])property_value.get_boxed());
}
}
return new GLib.Variant("s", "No property of type GStrv found");
}
int main() {
var foo = new Foo();
print("%s\n", first_gstrv_property_as_variant(foo).print(true));
foo.bar.set("baz", 42);
print("%s\n", first_gstrv_property_as_variant(foo).print(true));
foo.bar.set("zot", 3);
print("%s\n", first_gstrv_property_as_variant(foo).print(true));
return 0;
}
Output:
bar-keys
GStrv
#as []
bar-keys
GStrv
['baz']
bar-keys
GStrv
['baz', 'zot']
In the generated c-code this looks as follows:
_tmp18_ = g_value_get_boxed (&property_value);
_tmp19_ = g_variant_new_strv ((gchar**) _tmp18_, -1);
Passing -1 as length to g_variant_new_strv() means the string array is considered as null terminated. Inside g_variant_new_strv() the g_strv_length() function is used to determine the length.
Hopefully it will be useful to someone else someday. :-)

Test spray.io response

I have the next code:
//models
case class Foo(name: String, age: Option[Int] = None)
//routing
trait FooRouting extends HttpService {
def index(foos: List[Foo]): twirl.api.Html = html.foo.render(foos)
val route =
path("") {
get { complete( index(Foo.all) } }
}
}
In index method, i render foo.scala.html template with Twirl.
I want test this behaviour:
//tests
class FooTests extends FunSpec with Matchers
with ScalatestRouteTest {
def actorRefFactory = system
val t0 = Foo("test0")
val t1 = Foo("test1")
it("test foo") {
Get() ~> r ~> check {
responseAs[List[Foo]] should be(List(t0, t1))
}
}
}
But i got error:
Tests.scala:49: could not find implicit value for evidence parameter of type spray.httpx.unmarshalling.FromResponseUnmarshaller[List[pack.Foo]]
[error] responseAs[List[Foo]] should be(List(t0, t1))
I define implicit method:
implicit val foo2response = new FromResponseUnmarshaller[List[Foo]] {
def apply(r: HttpResponse): Deserialized[List[Foo]] = {
???
}
}
But i do not know what i should write into body.
Thanks.

Resources