How to use TypeToken + generics with Gson in Kotlin

Create this inline fun: inline fun <reified T> Gson.fromJson(json: String) = fromJson<T>(json, object: TypeToken<T>() {}.type) and then you can call it in this way: val turns = Gson().fromJson<Turns>(pref.turns) // or val turns: Turns = Gson().fromJson(pref.turns) Previous Alternatives: ALTERNATIVE 1: val turnsType = object : TypeToken<List<Turns>>() {}.type val turns = Gson().fromJson<List<Turns>>(pref.turns, turnsType) You have to put … Read more

Scala 2.8 CanBuildFrom

Note that the second argument to map is an implicit argument. There must be an implicit in scope with the appropriate types, or, otherwise, you must pass such an argument. In your example, That must be Set[String], B must be Int and Repr must be List[String]. Therefore, for that to compile you need the following … Read more

Generic repository in ASP.NET Core without having a separate AddScoped line per table in Startup.cs?

Just use the non-generic registration overloads (the ones where you need to pass the 2 Type objects.) Then provide the open generic types of both your interface and the implementation: services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>)); In your controller, add a dependency for a repository of a specific type (a closed generic type): public HomeController(IGenericRepository<Lookup1> repository) { … }

Why can’t I use a key function that returns a reference when sorting a vector with sort_by_key?

For now, you have to use the “long” form: v.sort_by(|x, y| key(x).cmp(&key(y))); Why am I getting these errors? Is there any way to fix them? The cause and fix are one-and-the same: Rust is simply not currently expressive enough to represent what you want. The feature needed is called generic associated types (GATs); previously known … Read more

Generic Functions in Go

As of Go 1.18 you can write a generic function Print as below: package main import ( “fmt” ) // T can be any type func Print[T any](s []T) { for _, v := range s { fmt.Print(v) } } func main() { // Passing list of string works Print([]string{“Hello, “, “world\n”}) // You can … Read more

How do I return a Filter iterator from a function?

Rust 1.26 fn filter_one(input: &[u8]) -> impl Iterator<Item = &u8> { input.iter().filter(|&&x| x == 1) } fn main() { let nums = vec![1, 2, 3, 1, 2, 3]; let other: Vec<_> = filter_one(&nums).collect(); println!(“{:?}”, other); } Rust 1.0 fn filter_one<‘a>(input: &’a [u8]) -> Box<Iterator<Item = &’a u8> + ‘a> { Box::new(input.iter().filter(|&&x| x == 1)) } … Read more