Scala generics - why I can't create parametrised object inside generic class? - scala

I'm currently learning scala.
Why this code doesn't work:
class GenClass[T](var d : T) {
var elems: List[T] = Nil
def dosom(x: T) = {
var y = new T()
y
}
}
I get:
error: class type required but T found
in place of var y - new T()
Is it because type erasing from java? Is there any way to solve this - create variable of type T inside generic function?

have a look at this question, there's an example of a factory:
How to instantiate an instance of type represented by type parameter in Scala

Because you can not be sure there always is a public, parameterless constructor.

Related

Enumeration subtype element as parameter in Scala

I have a generic class for which the type must be a subtype of Enumeration
class MyClass[A<: Enumeration](val parameter1 : Int,
val parameter2: A) {
}
Inside this class, there is a method that needs to take an element from the enum A as parameter. I cannot find the proper way to write the signature of the method.
def myMethod(element: A.Values): Resource2[A] = {
this
}
Intellisense says
Cannot resolve symbol A
How can I write the method so it takes an element of the enum A ?
The type is Value (not Values) and, because A is a type and not an instance (i.e. not a value), the syntax for referencing a type within a type is element: A#Value.

Generics in TypeScript: How to infer the type of an instance from the class

A factory function creates the instances of classes:
class A {
name: string
}
function factory<T>(Cl): T {
return new Cl()
}
let a = factory<A>(A)
a.name // OK
I would like to avoid the repetition of A in: factory<A>(A). The generics instance type should be able to be inferred from the class type, shouldn't be?
I tried this code:
function factory<T>(Cl: typeof T): T { // Error: Cannot find name 'T'
return new Cl()
}
Is there a way to do this?
Based on the Typescript documentation :
When creating factories in TypeScript using generics, it is necessary
to refer to class types by their constructor functions.
So you must do something like this:
function factory<T>(Cl: { new(): T; }): T {
return new Cl();
}
In the code above, Cl must a type that at least has a constructor which return T generic type.
So the type inference will work:
let a = factory(A);
a.name;
You don't need to specify the type of A anyway because the compiler know it.

In Swift, can Types (not instances) conform to protocols?

I have a ViewController that uses a class (call it A) from a framework outside of my control. A provides a class function I need (call it f). I want to make A easy to mock out in tests.
So my idea was to create a protocol P that has the same signature as A, extend A to implement P, and then create a mock class M that also implements P and has a dummy implementation of f. Then in my tests, I could just do viewController.dependency = M and everything should be dandy.
This is easier said than done, for reasons I'm hoping you'll help me understand.
Inside my viewController, it's easy to declare a variable that contains a protocol-conforming instance and then reassign the variable to another Protocol-conforming instance:
// works
var dependency: P = A()
dependency.f()
dependency = M()
dependency.f()
But it doesn't work to do the same thing with just the types:
// doesn't work
var dependency = A.self
dependency = M.self // cannot assign value of M.Type to a value of type A.Type
// also doesn't work
var dependency: P = A.self // type A.Type does not conform to protocol P
Is there a way to make this work? I thought maybe I could use a generic type for dependency but I can't figure out a syntax to declare a generic type for a variable assignment.
If you really want to store the type itself, you can use P.Type. The following works in Swift 2:
protocol P {
static func foo()
}
class A: P {
static func foo() { print("A foo") }
}
class M: P {
static func foo() { print("M foo") }
}
var dependency: P.Type = A.self
dependency = M.self
dependency.foo()
It doesn't work because when you say var dependency = A.self, the compiler infers, from the right-hand side, that dependency's type is A. That means that if dependency ever gets reassigned, it can be assigned only to some other instance of an A class type. When you created protocol P with the same signature as A, then a a class M that implements P, you still haven't (and can't, since it's out of your control) made A implement protocol P. The way the Swift and Objective-C runtimes work is that each object contains a pointer to its type class. This type is inspected when assigning, and if the right-hand value is being assigned to a left-hand declaration, then the right-hand value has to have the left-hand's type somewhere in its inheritance hierarchy.
Some languages (e.g. Ruby) feature so-called duck typing, where if an object or class walks like a duck, then it is a duck, even if it's not really an instance of a duck. That's what you're looking for here, but Swift (and Objective-C) don't work that way. Duck typing is a type of pseudo-polymorphism. It's not really polymorphic.

Defining explicit conversion for custom types in Swift

What is currently the best/preferred way to define explicit conversions in Swift? Of the top of my head I can think of two:
Creating custom initializers for the destination type via an extension, like this:
extension String {
init(_ myType: MyType) {
self = "Some Value"
}
}
This way, you could just use String(m) where m is of type MyType to convert m to a string.
Defining toType-Methods in the source type, like this:
class MyType {
func toString() -> String {
return "Some Value"
}
}
This is comparable to Swift's String.toInt(), which returns an Int?. But if this was the definitive way to go I would expect there to be protocols for the basic types for this, like an inversion of the already existing *LiteralConvertible protocols.
Sub-question: None of the two methods allow something like this to compile: let s: MyString = myTypeInstance (as String) (part in parentheses optional), but if I understand right, the as operator is only for downcasting within type hierarchies, is that correct?
The pattern used in swift is the initializer. So for instance when converting an Int to UInt, we have to write:
var i: Int = 10
var u: UInt = UInt(i)
I would stick with that pattern.
As for the subquestion, the documentation states that:
Type casting is a way to check the type of an instance, and/or to treat that instance as if it is a different superclass or subclass from somewhere else in its own class hierarchy.
and
You can also use type casting to check whether a type conforms to a protocol
so no, the as keyword can`t be used to transform a value of a certain type to another type.
That can be tested in a simple way:
var i: Int = 10
var u: UInt = i as UInt
That generates an error:
'Int' is not convertible to 'UInt'
More about Type Casting

How to initialize empty variables from your own type in Scala?

My problem is understanding is the syntax of Scala. I come from a Java background. I am trying to make a variable of the same type as the class it is in. Example:
class Exp {
var exp1: Exp;
}
I am getting this error:
Driver.scala:4: error: class Exp needs to be abstract, since variable exp1 is not defined
(Note that variables need to be initialized to be defined)
class Exp {
Can someone explain why I cannot do this? I am new to the language. Any explanation would help in understanding it better.
Because you need to initialize it. Otherwise the compiler thinks you want only the variable's interface: the getter and setter methods. It's very similar to how a method without a body is abstract. The following will initialize it to null and give you a valid concrete class with a concrete variable.
class Exp {
var exp1: Exp = _;
}
This use of _ means "default value" where the default is null for reference types and 0, false, or something similar for non-reference types.
Wildcard Initializer
in Scala 2:
var x: A = _
in Scala 3:
var x: A = scala.compiletime.uninitialized