Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #245 Print value of custom type

Print the value of object x having custom type T, for log or debug.

from typing import TypeVar
T = TypeVar('T')
x: T = 123
print(f'{x=}', type(x))
print(x)
#include <iostream>
std::cout << x;
print(x);
import fmt;
fmt.Println(x)
print x
console.log(x);
import static java.lang.System.out;
import java.util.Formatter;
class X<T> {
    T x;
    X(T x) { this.x = x; }
    public String toString() {
        var s = new StringBuilder();
        var f = new Formatter(s);
        f.format("%s", getClass().getName());
        f.format("<%s>", x.getClass().getName());
        f.format("@%x", hashCode());
        f.flush();
        return s.toString();
    }
}
X<?> x = new X<>(123);
out.println(x);
import static java.lang.System.out;
out.print(x);
writeln(x.T);
use Object::Pad;
class Point {
    has $x :param = 0;
    has $y :param = 0;
    
    use overload '""' => sub { shift->_stringify() };   

    method _stringify () { "A point at ($x, $y)"  }
}
 
my $p = Point->new(x => 5, y => 10);

print $p; # prints: A point at (5, 10)
package Point { 
    my $_data = {};
    
    sub new { 
        my $class = shift;
        $_data = { @_ };
        bless $_data, $class;
    };

    use overload '""' => sub { shift->_stringify() };

    sub _stringify {
        my $self = shift;
        return sprintf 'A point at (%d, %d)', $self->{x}, $self->{y};
    }
}
 
my $p = Point->new(x => 5, y => 10);
print $p;
puts x
println!("{:?}", x);
Debug.Print x

New implementation...
< >
花大喵